题目
Given an input string, reverse the string word by word.
答案
public class Solution {
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
// extract word, insert to a string buidler
int i = 0;
while(i < s.length()) {
char c = s.charAt(i);
if(c != ' ') {
// find next space, or end of string
int pos = s.indexOf(' ', i);
if(pos == -1) pos = s.length();
String word = s.substring(i, pos);
sb = sb.insert(0, word + " ");
i += word.length();
continue;
}
i++;
}
return sb.toString().trim();
}
}