leetcode_双指针 557. 反转字符串中的单词 III
557. 反转字符串中的单词 III
- 给定一个字符串 s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
- 思路:
- 1.首先用split()切割字符串中用空格分隔的单词
- 2.用切片法反转每个单词
- 3.用join()把反转后的单词用空格连接
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
# 使用split()按空格分割字符串
words = s.split()
# 反转每个单词
reversed_words = [word[::-1] for word in words]
# 使用join将反转后的单词用空格连接起来
return ' '.join(reversed_words)
- 时间复杂度: O(n)
- 空间复杂度: O(n)