151. Reverse Words in a String
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.
此题要注意裁剪空格。代码如下:
public class Solution {
public String reverseWords(String s) {
String[] str = s.trim().split("\\s+");
int left = 0;
int right = str.length-1;
while(left<right){
String temp = str[left];
str[left] = str[right];
str[right] = temp;
left++;
right--;
}
StringBuilder sb = new StringBuilder();
for(int i=0;i<str.length;i++){
if(i==str.length-1){
sb.append(str[i]);
}else{
sb.append(str[i]+" ");
}
}
return sb.toString();
}
}
我开始的时候想能不能用reverse来做,后来发现不行,reverse是把字母顺序完全变换了。