#151. 反转字符串里的单词

#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)。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值