您的位置:首页 > 其它

Reverse Words in a String--LeetCode

2017-10-31 19:34 453 查看

1.题目

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”.

Update (2015-02-12):

For C programmers: Try to solve it in-place in O(1) space.

2.题意

字符串反转

尝试在 O (1) 空间中就地解决它

3.分析

先将整个字符串翻转一次,再分别翻转每一个单词

或者先分别翻转每一个单词,然后再整个字符串翻转一次

4.代码

class Solution {
public:
void reverseWords(string &s) {
int len = s.size();
int index = 0;

reverse(s.begin(), s.end());

for(int i = 0; i < len; ++i)
{
if(s[i] != ' ')
{
if(index != 0)
s[index++] = ' ';

int j = i;
while(j < len && s[j] != ' ')
s[index++] = s[j++];

reverse(s.begin() + index - (j - i), s.begin() + index);

i = j;
}
}

s.resize(index);
}
};


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