Problem:
Given an input string, reverse the string word by word.For example,
Given s = "the sky is blue",
return "blue is sky the".
Java Code:
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0)
return s;
ArrayList<String> wordList = new ArrayList<String>();
StringBuilder subString = new StringBuilder();
StringBuilder result = new StringBuilder();
int index = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) != ' ')
subString.append(s.charAt(i));
else if (subString.length() != 0){
if (result.length() != 0)
result.append(" ");
result.append(subString.reverse());
subString = new StringBuilder();
index = i - 1;
}
}
if (subString.length() != 0) {
if (result.length() != 0)
result.append(" ");
result.append(subString.reverse());
}
return result.toString();
}
}
没有评论:
发表评论