Home

151. Reverse Words in a String

Detailed explanation coming soon!

public class Solution {
  public String reverseWords(String s) {
    if(s == null || s.length() < 1) return s;

    String[] words = s.trim().split(" ");
    Collections.reverse(Arrays.asList(words));

    StringBuilder builder = new StringBuilder(words[0]);

    for(int i = 1; i < words.length; i++) {
      String word = words[i].trim();

      if(word.length() > 0) {
        builder.append(" ");
        builder.append(words[i]);
      }
    }

    return builder.toString();
  }
}


Questions? Have a neat solution? Comment below!