[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

 

LeetCode All in One 題目講解匯總(持續更新中...) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM