天天看點

反轉字元串中的單詞 III

今天看到一道題,看一下題目要求。

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

輸入:“Let’s take LeetCode contest”

輸出:“s’teL ekat edoCteeL tsetnoc”

總體來說,難度不大,是以我就寫出了這樣的代碼:

class Solution:
    def reverseWords(self, s: str) -> str:
        tmp=s.split()
        ans_list=[]
        for i in tmp:
            i=list(i)
            i.reverse()
            ans="".join(i)
            ans_list.append(ans)
            print(ans)
        return " ".join(ans_list)      
class Solution:
    def reverseWords(self, s: str) -> str:
        return ' '.join(i[::-1] for i in s.split())