问题:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
Clarification:
- 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. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
解决:
① 直接解决,比较复杂,使用StringBuilder类的方法。
public class Solution { //21ms
public static String reverseWords(String s) {
if(s == null || s.length() == 0) return "";
s = s.trim();
String[] str = s.split("\\s+");
if(str.length == 1) return s;
StringBuilder sb = new StringBuilder();
for (int i = 0;i < str.length;i ++){
if(i > 0 && i <= str.length - 1){
sb.insert(0," ");
sb.insert(0,str[i]);
}else{
sb.insert(0,str[i]);
}
}
return sb.toString();
}
}
② 同上面一样,不过从后面向前扫描。
public class Solution {//8ms
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
s = s.trim();
String[] str = s.split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = str.length - 1; i >= 0; -- i) {
if (! str[i].equals("")) {
sb.append(str[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}
③ 在discuss中看到的。
public class Solution {
public String reverseWords(String s) {
String[] array = s.split(" ");
StringBuilder sb = new StringBuilder();
for(int i = array.length - 1; i >= 0; i --) {
if(array[i].length() > 0) sb.append(array[i]).append(" ");
}
return sb.toString().trim();
}
}