[LeetCode]Reverse Words in a String

来源:互联网 发布:笛子模仿软件 编辑:程序博客网 时间:2024/05/15 01:22

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.

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. 将整个字符串按照字母整个进行反转
2. 单词内进行反转,设置first和last分别表示单词的结束和开始,N个空格的第一个的前一个位置是单词的结尾,N个空格的最后一个的下一个是单词的开始。同时删去多余的空格。
3. 不额外使用存储空间。

下面贴上代码:

class Solution {public:    void reverseWords(string &s) {        reverse(s.begin(), s.end());        int first=0;        int last=0;        int i = 0;        while (first != s.length()){            while (first != s.length() && s[first] == ' ')                first++;            last = first;            while (last != s.length() && s[last] != ' ')                last++;            if (i != 0 && first <= last - 1)                s[i++] = ' ';            for (int j = last - 1; first < j; first++, j--){                swap(s[j], s[first]);                s[i++] = s[first];            }            while (first < last){                s[i++] = s[first++];            }        }        s.resize(i);    }};
0 0
原创粉丝点击