Leetcode 557 Reverse Words in a String Ⅲ
题目描述
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路解析
- 与Reverse String思路类似
class Solution:
def reverseWords(self, s: str) -> str:
result = s.split()
for index, item in enumerate(result):
temp = list(item)
self.reverseString(temp)
result[index] = ''.join(temp)
return ' '.join(result)
def reverseString(self, temp):
length = len(temp)
i = 0
j = length - 1
while i < j:
temp[i], temp[j] = temp[j], temp[i]
i += 1
j -= 1
时间夫复杂度为 O ( N ) , N 为 字 符 串 长 度 O(N),N为字符串长度 O(N),N为字符串长度,空间复杂度为 O ( N ) O(N) O(N)
注意:python中可变类型传参时为引用传递,不可变类型传参时为值传递
- 另外,也可以用栈来实现反转,遇到空格就将前面的单词反转
class Solution:
def reverseWords(self, s: str) -> str:
s = s + " "
stack = []
result = ""
for item in s:
stack.append(item)
if item == ' ':
while stack:
result = result + stack.pop()
return result[1:]
时间复杂度为 O ( N ) O(N) O(N),空间复杂度为 O ( N ) O(N) O(N)
本文详细解析了LeetCode第557题Reverse Words in a String III的解题思路,介绍了如何使用Python通过反转字符串中的每个单词来解决这个问题,同时保持句子中单词的初始顺序不变。文章提供了两种解决方案,一种是利用split和join方法,另一种是使用栈来实现单词的反转。

856

被折叠的 条评论
为什么被折叠?



