Leetcode刷題筆記python-----反轉字串中的單詞3
阿新 • • 發佈:2018-12-12
反轉字串中的單詞3
題目
給定一個字串,你需要反轉字串中每個單詞的字元順序,同時仍保留空格和單詞的初始順序。
示例 1:
輸入: “Let’s take LeetCode contest”
輸出: “s’teL ekat edoCteeL tsetnoc”
注意:在字串中,每個單詞由單個空格分隔,並且字串中不會有任何額外的空格。
解答
思路1:
- 按空格分開
- 每個單詞反轉
- 拼接在一起
- 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:
- 寫一個字元反轉函式
- 再遍歷
程式碼:
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]
結果:基本沒影響,所以函式無法加快效率??