C++實現LeetCode(186.翻轉字符串中的單詞之二)

[LeetCode] 186. Reverse Words in a String II 翻轉字符串中的單詞之二

Given an input string , reverse the string word by word. 

Example:

Input:  [“t”,”h”,”e”,” “,”s”,”k”,”y”,” “,”i”,”s”,” “,”b”,”l”,”u”,”e”]
Output: [“b”,”l”,”u”,”e”,” “,”i”,”s”,” “,”s”,”k”,”y”,” “,”t”,”h”,”e”]

Note: 

  • A word is defined as a sequence of non-space characters.
  • The input string does not contain leading or trailing spaces.
  • The words are always separated by a single space.

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

這道題讓我們翻轉一個字符串中的單詞,跟之前那題 Reverse Words in a String 沒有區別,由於之前那道題就是用 in-place 的方法做的,而這道題反而更簡化瞭題目,因為不考慮首尾空格瞭和單詞之間的多空格瞭,方法還是很簡單,先把每個單詞翻轉一遍,再把整個字符串翻轉一遍,或者也可以調換個順序,先翻轉整個字符串,再翻轉每個單詞,參見代碼如下:

解法一:

class Solution {
public:
    void reverseWords(vector<char>& str) {
        int left = 0, n = str.size();
        for (int i = 0; i <= n; ++i) {
            if (i == n || str[i] == ' ') {
                reverse(str, left, i - 1);
                left = i + 1;
            }
        }
        reverse(str, 0, n - 1);
    }
    void reverse(vector<char>& str, int left, int right) {
        while (left < right) {
            char t = str[left];
            str[left] = str[right];
            str[right] = t;
            ++left; --right;
        }
    }
};

我們也可以使用 C++ STL 中自帶的 reverse 函數來做,先把整個字符串翻轉一下,然後再來掃描每個字符,用兩個指針,一個指向開頭,另一個開始遍歷,遇到空格停止,這樣兩個指針之間就確定瞭一個單詞的范圍,直接調用 reverse 函數翻轉,然後移動頭指針到下一個位置,在用另一個指針繼續掃描,重復上述步驟即可,參見代碼如下:

解法二:

class Solution {
public:
    void reverseWords(vector<char>& str) {
        reverse(str.begin(), str.end());
        for (int i = 0, j = 0; i < str.size(); i = j + 1) {
            for (j = i; j < str.size(); ++j) {
                if (str[j] == ' ') break;
            }
            reverse(str.begin() + i, str.begin() + j);
        }
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/186

類似題目:

Reverse Words in a String III

Reverse Words in a String

Rotate Array

參考資料:

https://leetcode.com/problems/reverse-words-in-a-string-ii/

https://leetcode.com/problems/reverse-words-in-a-string-ii/discuss/53851/Six-lines-solution-in-C%2B%2B

https://leetcode.com/problems/reverse-words-in-a-string-ii/discuss/53775/My-Java-solution-with-explanation

到此這篇關於C++實現LeetCode(186.翻轉字符串中的單詞之二)的文章就介紹到這瞭,更多相關C++實現翻轉字符串中的單詞之二內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: