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
".
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.
- 题目大意:给定一个字符串,对字符串进行逆转。
- 解题思路:看到这道题目有两种思路:
1)用两个指针从前到后扫描,分开单词,先对每个单词进行逆转,最后再对整个字符串逆转;
比如题目中给的例子:先对每个单词进行逆转得到的结果:"eht yks si eulb",然后再整体逆转即可得到"blue is sky the"。
2)根据空格切分字符串,将切分得到的单词存到vector中,然后将vector中的单词从末尾开始输出即可。
在衡量了两种方法之后,觉得第二种方法代码更加简洁方便,便选择了第二种思路。
- 实现:
void reverseWords(string &s) {
int i=0,j=0;
int len = s.length();
vector<string> splitResult;
while(i<len)
{
if(s[i]==' ')
i++;
else
{
j=i+1;
while(j<=len)
{
if(s[j]==' '||j==len)
{
string tempStr = s.substr(i,j-i);
splitResult.push_back(tempStr);
i=j+1;
break;
}
else
j++;
}
}
}
int size = splitResult.size();
if(size>0)
{
s="";
for(i=size-1;i>0;i--)
s+=splitResult[i]+" ";
s+=splitResult[i];
}
else
{
s="";
}
}
注意的地方:我一开始提交就提示错误,要考虑到空字符串以及只有空格组成的字符串,因此要在最后作一个判断,如果splitResult为空,则直接把s赋值为""即可。