1
2
3
4
5
6
|
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. |
题意:反转字符串中的单词,注意空格的处理!!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class Solution {
public String reverseWords(String s) {
int length=s.length();
// char[] ch=s.toCharArray();
if (s== null || length== 0 ) return s;
int end=length;
StringBuilder ret= new StringBuilder();
for ( int i=length- 1 ;i>= 0 ;i--){
if (s.charAt(i)== ' ' )end=i;
else if (i== 0 || s.charAt(i- 1 )== ' ' ){
//如果里面有单词,新加单词时先加空格
if (ret.length()!= 0 )
ret.append( ' ' );
ret.append(s.substring(i,end));
}
}
return ret.toString();
}
} |
PS:群里大神思路。挺简洁的。从后往前遍历。找到单词就添加到ret,
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1902701