Description
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Thinking Process
- Get rid of leading and trailing spaces
- Get rid of extra spaces in between
- Split by space, and recreate the sentence using StringBuilder
Code
public class Solution {
public String reverseWords(String s) {
String s1 = s.trim();
String s2 = s1.replaceAll("\\s+", " ");
String[] words = s2.split(" ");
StringBuilder sb = new StringBuilder();
for(int i = words.length - 1; i >= 0; i--){
sb.append(words[i]);
sb.append(" ");
}
if(sb.length() == 0)
return "";
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}