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.
最基本的解决方案,非原地翻转,用python和c可以很容易解决,但空间复杂度较大,思路是先split成数组,对数组做翻转再还原
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
L = s.split()#字符串以单词分隔成列表
L.reverse()#反转列表中的单词
s1 = ' '.join(L)#以空格分隔列表中反转后的单词,返回字符串
return s1
但是基于原地翻转空间复杂度O(1)的方法就没法用python了,使用c解决, 思路是先给每个单词词内进行翻转,然后对整个句子以字母为最小单位翻转,最后去除掉多余的空格。
void reverseWords(char *s) {
int i = 0;
int start=0;
int end=0;
while (s[i]){
if (i == 0 || (s[i]!= ' ' && s[i-1]==' ') ) {
start = i;
}
if (!s[i] || (s[i]!=' ' && s[i+1] == ' ') ){
end = i;
reverse_substring(s,start,end);
}
printf("i = %d, start = %d, end = %d ,%s\n",i,start,end,s);
i++;
}
int last = i-1;
reverse_substring(s,start,last);
reverse_substring(s,0,last);
//check ' '
i = 0;
int lastLetter = -1;
while (s[i]){
if (s[i] != ' ') {
lastLetter = i;
}
i++;
}
s[lastLetter+1] = '\0';
}
void reverse_substring(char *s,int start,int end){
for(int i=0;i<=(end-start)/2;i++)
{
char tmp = s[start+i];
s[start+i] = s[end-i];
s[end - i] = tmp;
}
}