leetcode 2645. 构造有效字符串的最少插入数-python

题目:
给你一个字符串 word ,你可以向其中任何位置插入 “a”、“b” 或 “c” 任意次,返回使 word 有效 需要插入的最少字母数。

如果字符串可以由 “abc” 串联多次得到,则认为该字符串 有效 。
在这里插入图片描述

解题方法

1.先判断字符串是否全是由abc组成
2.判断字符串是否全是由单个a或b或c组成
3.字符串长度为2,只需添加一次情况
4.遍历

  • 使用for循环会出现 for i in range(s) 在循环里i+n无效 如:当前i= 2 循环里i+2 4,进入下一次循环
    i为i+1 即3 所以用while循环,用while,则需先定义当前i为0,且i<len(word)

  • 字符判断时,首先先判断是否是字符串中的最后一个字符,是则不再进行后续的循环

  • 不是最后一个字符,接着判断n种情况,ab、ac、bc、abc、a、b、c这几种情况需要添加字符数量,下一轮从哪个字符开始遍历

代码:

class Solution(object):
    def addMinimum(self, word):
        """
        :type word: str
        :rtype: int
        """
        s=len(word)
        #判断字符串是否全是由abc组成
        if s==0 or (word.count('abc') == s/3 and s%3==0):
            return 0
        #字符串是否全是由单个a或b或c组成
        elif word.count(word[0])== s:
            return s*2
        #字符串长度为2,只需添加一次情况
        elif s==2 and word in ('ab','ac','bc'):
            return s//2
        count =0
        i = 0
        #遍历
        while i<s:
            if word[i] =='a' and i<s:
                #当前字符是否是字符串最后一个字符
                if i+1 ==s:
                    count+=2
                    break
                if word[i+1] =='b' and i+1<s:
                    if i+2==s:
                        count+=1
                        break
                    if word[i+2] =='c' and i+2<s:
                        if i+3==s:
                            break
                        i+=3
                    else:
                        count+=1
                        i+=2
                elif word[i+1] =='c' and i+1<s:
                    if i+2==s:
                        count+=1
                        break
                    count+=1
                    i+=2
                else:
                    count+=2
                    i+=1
                
            elif word[i]=='b' and i<s:
                if i+1==s:
                    count+=2
                    break
                if word[i+1] =='c' and i+1<s:
                    if i+2==s:
                        count+=1
                        break
                    count+=1
                    i+=2
                else:
                    count+=2
                    i+=1
            else:
                if i+1==s:
                    count+=2
                    break
                count+=2
                i+=1
        return count
  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值