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)