[Leetcode]Reverse Words in a String

98人阅读 评论(0)

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.

click to show clarification.

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.

class Solution {
public:
/*algorithm
reverse whole sentence
reverse word by word
time O(n) space O(1)
*/
void reverse(string &s,int start,int len){
int i = 0,j = len-1;
while(i < j){
swap(s[start+i],s[start+j]);
i++,j--;
}
}
void reverseWords(string &s) {
//space pre-process,remove leading and trailing spaces,reduce words space to 1
int k = 0;
for(int i = 0;i < s.size();i++){
if(s[i] != ' '){
if(i&&s[i-1]==' '&&k)s[k++] = ' ';
s[k++] = s[i];
}
}
s.resize(k);

reverse(s,0,s.size());
for(int i = 0;i < s.size();){
int j = i;
while(j+1 < s.size() && s[j+1] != ' ')++j;
reverse(s,i,j-i+1);
i = j+2;
}
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：28497次
• 积分：2222
• 等级：
• 排名：第16952名
• 原创：202篇
• 转载：6篇
• 译文：0篇
• 评论：1条
阅读排行