您的位置:首页 > 其它

Reverse Words in a String

2014-03-24 16:14 190 查看
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.

些麻烦了,懒得改。对于空格,只要while就能解决。
注意,string 和 char *是不一样的。

class Solution {
public:
void reverseWords(string &s) {
stack<string> sk;
if(s.size()==0)return ;
int i = 0;
int b = 0,e = 0;
if(s.size()==1)
{
if(s[0] == ' ')
{
s = "";
return;
}
else return;
}
for(i = 0 ; i < s.size()-1;i++)
{
if(s[i] == ' '&&s[i+1] != ' ')
{
b = i+1;
}
else if(s[i] != ' ' && s[i+1] == ' ')
{
e = i+1;
string tp = s.substr(b,e-b);
sk.push(tp);
}
}
if(s[s.size()-1] != ' ')
{
string tp = s.substr(b,s.size());
//  if(b != e)
{
sk.push(tp);
}
}

if(sk.empty())
{
s="";
return;
}
s = sk.top();
sk.pop();

while(!sk.empty())
{
string tp = sk.top();
s = s + ' '+tp;
sk.pop();
}
//s = s+'\0';
}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: