LeetCode-每日練習(xí):顛倒字符串中的單詞

151. 顛倒字符串中的單詞

給你一個(gè)字符串 s ,顛倒字符串中 單詞 的順序。
單詞 是由非空格字符組成的字符串。s 中使用至少一個(gè)空格將字符串中的 單詞 分隔開。
返回 單詞 順序顛倒且 單詞 之間用單個(gè)空格連接的結(jié)果字符串。
注意:輸入字符串 s中可能會(huì)存在前導(dǎo)空格、尾隨空格或者單詞間的多個(gè)空格。返回的結(jié)果字符串中,單詞間應(yīng)當(dāng)僅用單個(gè)空格分隔,且不包含任何額外的空格。

輸入:s = "the sky is blue"
輸出:"blue is sky the"

  • 方法1:切片+反轉(zhuǎn)+列表轉(zhuǎn)為字符串
class Solution:
    def reverseWords(self, s: str) -> str:
        word = s.split(' ')
        # print(word)
        res = []
        for w in word:
            if w != '':
                res.append(w)
        return ' '.join(res[::-1])
  • 方法2:模擬算法+雙指針
class Solution:
    def reverseWords(self, s: str) -> str:
        res = []
        word = ''
        for ch in s:
            if ch == ' ':
                # 當(dāng)字符串非空
                if word:
                    # 添加新的單詞
                    res.append(word)
                    # 單詞重置
                    word = ''
            else:
                word += ch
        # 添加最后一個(gè)單詞
        if word:
            res.append(word)
        # 雙指針交換位置
        for i in range(len(res)//2):
            res[i], res[len(res)-i-1] = res[len(res)-i-1], res[i]
        return ' '.join(res)

?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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