Given an input string, reverse the string word by word.
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
public class Solution {
public String reverseWords(String s) {
ArrayList<String> result = new ArrayList<String>();
String resultString = "";
if (s.length() == 0) {
return resultString;
}
String remainingWords = s;
while(remainingWords != null) {
remainingWords = getFirstWord(remainingWords, result);
}
if (result.size() == 0) {
return resultString;
}
Collections.reverse(result);
for(String str:result) {
resultString += " " + str;
}
return resultString.substring(1);
}
public String getFirstWord(String str, ArrayList<String> words) {
String word = "";
int i;
int length = str.length();
for (i = 0; i < length; i++) {
if (str.charAt(i) != ' ') {
break;
}
}
if (i == length) {
return null;
}
else {
String remains = str.substring(i);
int remainLength = remains.length();
for (i = 0; i < remainLength; i++) {
if (remains.charAt(i) != ' ') {
word += remains.charAt(i);
}
else {
break;
}
}
words.add(word);
if (i == remainLength) {
return null;
}
else {
return remains.substring(i);
}
}
}
}