1. 程式人生 > >leetcode-557. 反轉字串中的單詞 III

leetcode-557. 反轉字串中的單詞 III

一、問題描述

給定一個字串,你需要反轉字串中每個單詞的字元順序,同時仍保留空格和單詞的初始順序。

示例 1:

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

注意:在字串中,每個單詞由單個空格分隔,並且字串中不會有任何額外的空格。

二、程式碼和思路

1.將字串轉換成列表

2.將兩個空格間的字元倒序

3.將列表轉換成字串

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        s=list(s)
        i,j,n=0,0,len(s)
        while i<n:
            while i<n and s[i] !=' ':
                i += 1
            for k in range((i-j)//2):
                s[j+k],s[i-1-k]=s[i-1-k],s[j+k]
            i += 1
            j=i
        return ''.join(s)

三、執行結果