[leetcode] 186. Reverse Words in a String II 解题报告

题目链接: https://leetcode.com/problems/reverse-words-in-a-string-ii/

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Could you do it in-place without allocating extra space?

Related problem: Rotate Array


思路: 两次翻转即可, 单词翻转一次, 然后整体翻转一次.

代码如下: 

class Solution {
public:
    void reverseWords(string &s) {
        int k = 0, len = s.size();
        while(k < len)
        {
            auto pos = s.find(' ', k);
            if(pos != string::npos)
            {
                reverse(s.begin()+k, s.begin()+pos);
                k = pos+1;
            }
            else
            {
                reverse(s.begin()+k, s.end());
                break;
            }
        }
        reverse(s.begin(), s.end());
    }
};


你可能感兴趣的:(LeetCode,String)