您的位置:首页 > 其它

[leetCode]Reverse Words in a String

2014-03-08 15:50 489 查看
Given an input string, reverse the string word by word.

For example,
Given s = "
the sky is blue
",
return "
blue is sky the
".

注意考虑有多个空格的情况就好了,选择的处理办法是在进行空格查找之前先整理字符串

#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
void reverseWords(string &s) {
checkString(s);
size_t found;
string str;
found = s.find_last_of(" ");
while(found != string::npos){
str += s.substr(found+1) + " ";
s = s.substr(0,found);
found = s.find_last_of(" ");
}
str+=s;
s = str;
}
void checkString(string &s){
while(s[0] == ' ') s.erase(0,1);
if(s.size() == 0)    return;
while(s[s.size()-1] == ' ') s.erase(s.size()-1);
for(int i = 0; i < s.size()-1;i++){
if(s[i] == ' ' && s[i+1] == ' ') {
s.erase(i--,1);
}
}
return ;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: