LeetCode筆記:557. Reverse Words in a String III

問(wèn)題(Easy):

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.

大意:

給出一個(gè)字符串,你需要翻轉(zhuǎn)句子中每個(gè)單詞的字母,但保證空格位置以及原始的單詞順序不變。

例1:
輸入:"Let's take LeetCode contest"
輸出: "s'teL ekat edoCteeL tsetnoc"

注意:在字符串中,每個(gè)單詞都被單個(gè)空格分開,不會(huì)有額外的空格。

思路:

遍歷字符串,沒(méi)遇到一個(gè)空格就開始處理前面的這個(gè)單詞,將其用一些方式進(jìn)行反轉(zhuǎn)后存入新的字符串中,然后記得在新字符串后面加個(gè)空格(最后一個(gè)單詞就不要加空格了)。

如何對(duì)單詞反轉(zhuǎn)有多種方式,可以用一個(gè)臨時(shí)容器來(lái)存儲(chǔ),遇到單詞中每個(gè)字母都將其插入到容器首部,然后再將整個(gè)容器的內(nèi)容放到字符串中就好了。這個(gè)容器可以是deque這種允許兩端插入的,也可以就是string。但是用string(49ms)居然比用在首部插入應(yīng)該更快的deque(768ms)要快得多。

代碼(C++):

// 用deque
class Solution {
public:
    string reverseWords(string s) {
        deque<char> que;
        string res = "";
        for (int i = 0; i < s.length(); i++) {
            if (s[i] != ' ') {
                que.push_front(s[i]);
            } else {
                auto iter = que.begin();
                while (iter != que.end()) {
                    res = res + *iter;
                    iter++;
                }
                que.clear();
                res = res + " ";
            }
        }
        auto iter = que.begin();
        while (iter != que.end()) {
            res = res + *iter;
            iter++;
        }
        return res;
    }
};

// 用string
class Solution {
public:
    string reverseWords(string s) {
        string res = "";
        int pos = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s[i] != ' ') {
                res.insert(pos, s.substr(i, 1));
            } else {
                res = res + " ";
                pos = i + 1;
            }
        }
        return res;
    }
};

他山之石:

原來(lái)C++可以直接操作讓string的部分區(qū)間進(jìn)行反轉(zhuǎn),那就只需要記錄空格的位置,然后將之間的區(qū)域進(jìn)行反轉(zhuǎn)就行了,也不用創(chuàng)建結(jié)果字符串,直接在原字符串上操作即可,速度快了一倍。

class Solution {
public:
    string reverseWords(string s) {
        for (int i = 0; i < s.length(); i++) {
            if (s[i] != ' ') {   // when i is a non-space
                int j = i;
                for (; j < s.length() && s[j] != ' '; j++) { } // move j to the next space
                reverse(s.begin() + i, s.begin() + j);
                i = j - 1;
            }
        }
        
        return s;
    }
};

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁(yè)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容