您的位置:首页 > 其它

[LeetCode]Reverse Words in a String

2014-03-09 19:02 555 查看
原题链接:http://oj.leetcode.com/problems/reverse-words-in-a-string/

题目描述:

Given an input string, reverse the string word by word.

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

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.

题解:

  这道题真的很简单,尤其是用Java、C#这种对字符串操作的封装已经很强大的语言来写。我是用的C++来写的,稍微麻烦一点点。

string Rtrim( string &str ){
str.erase(std::find_if(str.rbegin(), str.rend(),std::not1(std::ptr_fun(::isspace))).base(),str.end());
return str;
}
void reverseWords(string &s){
vector<string> strs;
int len = s.length();
int start,end;
bool flag = false;
for(int i=0; i<len; i++){
if(s[i]!=' ' && !flag){
start = i;
flag = true;
}else if(s[i]==' ' && flag){
end = i;
flag = false;
strs.push_back(s.substr(start,end-start));
}
}
if(flag){
strs.push_back(s.substr(start,len-start));
}
s = "";
while( !strs.empty() ){
s+=strs.back();
s+=" ";
strs.pop_back();
}
s = Rtrim(s);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: