[LeetCode] 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.

click to show clarification.

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.

 

这道题让我们翻转字符串中的单词,题目中给了我们写特别说明,如果单词之间遇到多个空格,只能返回一个,而且首尾不能有单词,并且对C语言程序员要求空间复杂度为O(1),所以我们只能对原字符串s之间做修改,而不能声明新的字符串。那么我们如何翻转字符串中的单词呢,我们的做法是,先分别翻转每一个单词,然后再整个字符串整体翻转一次,此时就能得到我们需要的结果了。那么这里我们需要定义一些变量来辅助我们解题,i,j,k 和 wordCount,其中i为遍历s的位置,j为改写s的位置,k为当前单词的起始位置,wordCount为当前单词的个数。我们还需要写一个范围s中[i,j]范围内字符串的函数来帮助我们翻转单词。我们开始循环,首先将开头的空格都过掉,然后开始找单词,并覆盖s开头的位置,然后进行翻转,在单词中间插入一个空格,再继续找下一个单词,再进行翻转,以此类推,直到i和s的长度相等了停止。此时我们更改s的大小,去除掉多余的空格,然后再整体翻转一遍,就可以得到我们需要的结果,代码如下:

 

class Solution {
public:
    void reverseWords(string &s) {
        int i = 0, j = 0, k = 0, wordCount = 0;
        while (true) {
            while (i < s.size() && s[i] == ' ') ++i;
            if (i == s.size()) break;
            if (wordCount) s[j++] = ' ';
            k = j;
            while (i < s.size() && s[i] != ' ') {
                s[j] = s[i];
                ++j; ++i;
            }
            reverseWord(s, k, j - 1);
            ++wordCount;
        }
        s.resize(j);
        reverseWord(s, 0, j - 1);
    }
    void reverseWord(string &s, int i, int j) {
        while (i < j) {
            char t = s[i];
            s[i++] = s[j];
            s[j--] = t;
        }
    }
};

 

参考资料:

https://leetcode.com/discuss/16669/c-solution-in-place-runtime-o-n-memory-o-1

 

LeetCode All in One 题目讲解汇总(持续更新中...)

你可能感兴趣的:(LeetCode)