Description:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
- 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.
这道题就是一个简单的字符串处理的题目,题目很简单,方法很多。做这类题目最讨厌的就是单词间和整个string开头和结尾的空格,做string类题目可以先做一下预处理,把多余的空格去掉。另外一个难点就是如何精准的定位一个word。我如下的solution中做法是用一个flag表示现在是在找word的起点或是终点。flag为true表示寻到起点,为false表示寻找终点。最好还要注意最后一个单词的处理,for循环完后,如果flag为false表示最后一个单词未做处理。找到每个word 后,就放到一个stack中,最后出栈拼出最终的string.
Solution:
class Solution
{
public:
void reverseWords(string &s)
{
stack<string> ss;
bool flag=true;//Find the head of a new word if flag is "ture",else find the end of a new word
string::iterator beg,it;
for(it=s.begin();it!=s.end();++it)
{
if(flag && *it!=' ')
{
beg=it;
flag=!flag;
}
else if(!flag && *it==' ')
{
string temp(beg,it);
ss.push(temp);
flag=!flag;
}
}
if(flag == false)ss.push(string(beg,it));
s="";
while(!ss.empty())
{
s+=ss.top();
ss.pop();
if(!ss.empty())s+=" ";
}
}
};