LeetCode解題之Reverse Words in a String
原題
將一個字符串依照單詞的力度進行反轉。例如將”the sky is blue”轉化爲”blue is sky the”。
注意點:
- 原始字符串中可能首位有空格,結果不要有這些空格
- 原始字符串單詞間可能有多個空格,結果單詞間只需有一個空格
例子:
輸入: s = “the sky is blue”
輸出: “blue is sky the”
解題思路
用Python解決這個問題有些特殊,Python中的字符串是不可變的數據類型,而比較pythonic的寫法是直接一行代碼,先把字符串按空格分開,反轉後用空格連接起來。
從算法層面講,這道題希望做到原地完成字符串的反轉。我們可以通過以下幾步做到:
- 將整個字符串直接反轉
- 遍歷字符串單獨將每個單詞反轉,注意反轉的同時可以通過移位來除去不必要的空格
AC源碼
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return " ".join(s.split()[::-1])
if __name__ == "__main__":
assert Solution().reverseWords("the sky is blue ") == "blue is sky the"
歡迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 來獲得相關源碼。