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

[LeetCode] 557.Reverse Words in a String III 翻轉字符串中的單詞之三

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

這道題讓我們翻轉字符串中的每個單詞,感覺整體難度要比之前兩道Reverse Words in a String II和Reverse Words in a String要小一些,由於題目中說明瞭沒有多餘空格,使得難度進一步的降低瞭。首先我們來看使用字符流處理類stringstream來做的方法,相當簡單,就是按順序讀入每個單詞進行翻轉即可,參見代碼如下:

解法一:

class Solution {
public:
    string reverseWords(string s) {
        string res = "", t = "";
        istringstream is(s);
        while (is >> t) {
            reverse(t.begin(), t.end());
            res += t + " ";
        }
        res.pop_back();
        return res;
    }
};

下面我們來看不使用字符流處理類,也不使用STL內置的reverse函數的方法,那麼就是用兩個指針,分別指向每個單詞的開頭和結尾位置,確定瞭單詞的首尾位置後,再用兩個指針對單詞進行首尾交換即可,有點像驗證回文字符串的方法,參見代碼如下:

解法二:

class Solution {
public:
    string reverseWords(string s) {
        int start = 0, end = 0, n = s.size();
        while (start < n && end < n) {
            while (end < n && s[end] != ' ') ++end;
            for (int i = start, j = end - 1; i < j; ++i, --j) {
                swap(s[i], s[j]);
            }
            start = ++end;
        }
        return s;
    }
};

類似題目:

Reverse Words in a String II

Reverse Words in a String

參考資料:

https://discuss.leetcode.com/topic/85773/nothing-fancy-straight-java-stringbuilder

https://discuss.leetcode.com/topic/85797/java-two-methods-3-line-using-built-in-and-char-array

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

推薦閱讀: