题目描述:
Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue",
Output: "blue is sky the".
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up: For C programmers, try to solve it in-place in O(1) space.
解题方法就是把整个字符串翻转,然后再依次对每个单词翻转,对单词翻转可以利用两个指针实现,一个标记单词开头,一个标记单词末尾,同时要注意除去字符串首尾的空格。
class Solution {
public:
void reverseWords(string &s) {
while(!s.empty()&&s[0]==' ') s.erase(0,1);
while(!s.empty()&&s[s.size()-1]==' ') s.erase(s.size()-1,1);
reverse(s.begin(),s.end());
int i=0;
int j=0;
while(j<s.size())
{
if(j==s.size()-1)
{
reverse(s.begin()+i,s.begin()+j+1);
break;
}
else if(s[j]==' ')
{
reverse(s.begin()+i,s.begin()+j);
j++;
while(s[j]==' ') s.erase(j,1);
i=j;
}
else j++;
}
}
};
本文介绍了一种算法,用于将输入字符串中的单词顺序进行反转。通过整体翻转字符串再单独翻转每个单词来实现,有效处理了多余空格问题。
2887

被折叠的 条评论
为什么被折叠?



