您的位置:首页 > 其它

[LeetCode刷题记录]Reverse Words in a String

2015-04-08 12:58 302 查看
Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

思路:每次遇到空格把每个单词反转,然后把整个字符串反转。

边界条件注意:开始的多个空格跳过,结尾的多个空格删掉。单词中间间隔的多个空格变成一个。

建议实现,就是把处理空格的字符串从字符串开始重写,然后反转单词。

然后把字符串resize(),删掉多余的内容。

class Solution {
public:
void reverse(string &s, int i, int j){
while(i<j){
char t=s[i];
s[i++]=s[j];
s[j--]=t;
}
}

void reverseWords(string &s) {

int i=0, j=0;
int l=0;
int len=s.length();
int wordcount=0;

while(true){
while(i<len && s[i] == ' ') i++;  // 跳过前面空格
if(i==len) break;
if(wordcount) s[j++]=' '; //除了了第一个以外,其他情况后一位变空格
l=j;
while(i<len && s[i] != ' ') {s[j]=s[i]; j++; i++;} //拷贝覆盖
reverse(s,l,j-1);                // 反转每个单词
wordcount++;

}

s.resize(j);                           // resize result string
reverse(s,0,j-1);                  // reverse whole string
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: