C语言LeetCode每日一题(2024-1-11)2645.构造有效字符串的最小插入数

原题链接:. - 力扣(LeetCode)

一开始没想太多,把每一种情况的边界确定后就开始了模拟:

int addMinimum(char * word){
    char dic[3]={'a','b','c'};//存字典
    int i=0,start=0,res=0;
    int n=strlen(word);
    while(start<n){
        if(dic[i%3]==word[start]){//当前想要的字母与word字母相同
            i++;
            start++;
        }
       else if(dic[i%3]=='a'){
            if(word[start]=='b'){
               i++;
               res++;
           }
           else{
               res+=2;
               i+=2;
           }
           }
        else if(dic[i%3]=='b'){
            if(word[start]=='a'){
                res+=2;
                i+=2;
            }
            else{
                res++;
                i++;
            }
        }
        else{
            i++;
            res++;
        }
       }
    return res+'c'-word[start-1];
}

写完后发现太繁琐,应该有更好的方法,仔细阅读代码发现,其实无疑就两种情况:

1.当前word[i]大于word[i-1],则这两个字母应该在同一个‘abc’中

2.当前word[i]小于word[i-1],则这两个字母在不同'abc'中

int addMinimum(char * word) {
    int len = strlen(word);
    int res = 0;
    for (int i = 1; i < len; i++) {
        res+=(word[i]-word[i-1]+2)%3;//实际把各类模拟都包括进去
    }
    return res+word[0]+2-word[len-1];//头尾两个单独处理
}

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值