151题:翻转字符串里的单词

翻转字符串里的单词 

class Solution:
    def reverseWords(self, s: str) -> str:
        # 解法一:生撕代码
        s = list(s)
        while s[0] == ' ' or s[-1] == ' ':
            # s.remove(' ')
            del s[0]
            del s[-1]
            
        # slow = 0
        # fast = 0
        # for i in range(len(s)):
        #     if s[slow]
        # for循环中,列表s变化时,不能及时更新
        # for i in range(len(s)):
        #     if s[i] == ' ':
        #         if s[i + 1] == ' ':
        #             del s[i]
        #             i -= 1

        # i未定义
        i = 0
        # IndexError: list index out of range
        # 删除多余的空格,设计精妙
        while i < len(s) - 1:
            if s[i] == ' ':
                if s[i + 1] == ' ':
                    del s[i]
                    i -= 1
            i += 1
        # 进行总体的列表翻转
        left = 0
        right = len(s) - 1
        while left < right:
            temp = s[left]
            s[left] = s[right]
            s[right] = temp
            left += 1
            right -= 1
            
        left_record = 0
        # range(s) 不正确
        for j in range(len(s)):
            if s[j] == ' ':
                j_ = j
                while left_record < j - 1:
                    temp = s[left_record]
                    s[left_record] = s[j - 1]
                    s[j - 1] = temp
                    left_record += 1
                    j -= 1
                left_record = j_ + 1
            elif j == len(s) - 1:
                j_ = j
                while left_record < j:
                    temp = s[left_record]
                    s[left_record] = s[j]
                    s[j] = temp
                    left_record += 1
                    j -= 1
                left_record = j_ + 1
        s = ''.join(s)
        return s

主要总结如下:对于for循环结构和while循环结构:

# for循环中,列表s变化时,不能及时更新
# for i in range(len(s)):
#     if s[i] == ' ':
#         if s[i + 1] == ' ':
#             del s[i]
#             i -= 1

while循环中就可以自动及时更新:

while i < len(s) - 1:
     if s[i] == ' ':
        if s[i + 1] == ' ':
           del s[i]
           i -= 1
      i += 1

 del s[i]可以依据数组标签删除指定的元素

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值