1. 程式人生 > >Leetcode刷題筆記python-----反轉字串中的單詞3

Leetcode刷題筆記python-----反轉字串中的單詞3

反轉字串中的單詞3

題目

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

示例 1:

輸入: “Let’s take LeetCode contest”
輸出: “s’teL ekat edoCteeL tsetnoc”
注意:在字串中,每個單詞由單個空格分隔,並且字串中不會有任何額外的空格。

解答

思路1

  1. 按空格分開
  2. 每個單詞反轉
  3. 拼接在一起
  4. O(2)?

程式碼:

class Solution:
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
words=s.split(' ') res='' for i in words: n=len(i) for j in range(n): res+=i[n-j-1] res+=' ' return res[:-1]

結果:只打敗了10%左右的對手,,還需改進
少用迴圈?????

思路2

  1. 寫一個字元反轉函式
  2. 再遍歷

程式碼:

class Solution:
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
def strreverse(x): res='' n=len(x) for i in range(n): res+=x[n-i-1] return res words=s.split(' ') res='' for i in words: res=res+strreverse(i)+' ' return res[:-1]

結果:基本沒影響,所以函式無法加快效率??