#151. 反转字符串里的单词
题目
给定字符串s,反转s中单词的顺序。
-
s可能会由起头的多个空格,末尾的多个空格,以及单词与单词之间的多个空格。要求的输出在单词间只能包含一个空格。
-
Input: s = "the sky is blue" Output: "blue is sky the"
-
Input: s = " hello world " Output: "world hello"
解答
四步走:
- 先把原字符串里所有的多余空格去掉,输出其list形式
- 翻转list,使单词的次序倒转。
- 将每个单词的字符调转,成为原单词。
- 返回string形式的该list
class Solution:
def trim_spaces(self, s: str) -> list:
#remove leading and trailing spaces
left, right = 0, len(s) - 1
while s[left] == ' ':
left += 1
while s[right] == ' ':
right -= 1
#now remove duplicate spaces by constructing a string separated by single space
trimed = []
while left <= right:
if s[left] != ' ':
trimed.append(s[left])
elif s[left - 1] != ' ':
trimed.append(s[left])
left += 1
return trimed
def reverse_string(self, l : list, left : int, right : int) -> None:
#reverse string (here l) from position left to right
while left < right:
l[left], l[right] = l[right], l[left]
left += 1
right -= 1
def reverse_each_word(self, l : list) -> None:
#reverse each word in the list l
start, end = 0, 0
print(l)
while start < len(l):
while end < len(l) and l[end] != ' ':
end += 1
self.reverse_string(l, start, end - 1)
start = end + 1
end = start
def reverseWords(self, s: str) -> str:
#trim spaces, reverse entire string, reverse each word, join
trimmed = self.trim_spaces(s)
self.reverse_string(trimmed, 0, len(trimmed) - 1)
self.reverse_each_word(trimmed)
return "".join(trimmed)
收获
- bug出现在扫描整个list时,给空格相间的最后一个单词调序时。
- 最后一个单词这里,不能使用条件:当 l[end] != 空格时,增加 end,不然会造成end无限大。
- 应该使用条件:当 end < len(l) 时,增加end。这样end到末尾会更新为 len(l)。