拟人算法系列文章,以容易理解的方式描述算法,点赞收藏不迷路
反转字符串里的单词
class Solution:
def reverse_words(self, s: str) -> str:
words = s.split()
lo, hi = 0, len(words) - 1
while lo < hi:
words[lo], words[hi] = words[hi], words[lo]
lo += 1
hi -= 1
return " ".join(words)
if __name__ == '__main__':
s = "the sky is blue"
print(Solution().reverse_words(s)) # "blue is sky the"
和反转字符串同理,只是将字符串按空格分割成列表