LeetCode解法汇总2645. 构造有效字符串的最少插入数

目录链接:

力扣编程题-解法汇总_分享+记录-CSDN博客

GitHub同步刷题项目:

https://github.com/September26/java-algorithms

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

描述:

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

如果字符串可以由 "abc" 串联多次得到,则认为该字符串 有效 。

示例 1:

复制代码
输入:word = "b"
输出:2
解释:在 "b" 之前插入 "a" ,在 "b" 之后插入 "c" 可以得到有效字符串 "abc" 。

示例 2:

复制代码
输入:word = "aaa"
输出:6
解释:在每个 "a" 之后依次插入 "b" 和 "c" 可以得到有效字符串 "abcabcabc" 。

示例 3:

复制代码
输入:word = "abc"
输出:0
解释:word 已经是有效字符串,不需要进行修改。 

提示:

  • 1 <= word.length <= 50
  • word 仅由字母 "a"、"b" 和 "c" 组成。

解题思路:

本来想用动态规划什么的,后来发现,并不需要。

设置index记录位置,取index位置的前3位,如果等于abc,则index+3,不需要插入字母;

取index位置的前2位,如果等于ab,bc,ab,则需要插入一个1个字母,index+2;

否则,需要插入2个字母,index+1。

代码:

复制代码
public class Solution2645 {

    public int addMinimum(String word) {
        int index = 0;
        int result = 0;
        while (index < word.length()) {
            if ("abc".equals(word.substring(index, index + Math.min(3, word.length() - index)))) {
                index += 3;
                continue;
            }
            String two = word.substring(index, index + Math.min(2, word.length() - index));
            if ("ab".equals(two) || "bc".equals(two) || "ac".equals(two)) {
                index += 2;
                result += 1;
                continue;
            }
            index += 1;
            result += 2;
        }
        return result;
    }
}
相关推荐
荆棘鸟智能1 小时前
扬尘在线监测数据接入与异常清洗:从断点补传到质量审计
人工智能·算法·系统架构
文丑颜不良啊1 小时前
LeetCode926~950题目解析
java·leetcode
动词ing1 小时前
【题目练习】旋转图像
算法
天疆说1 小时前
【无标题】
算法
海绵宝宝的月光宝盒1 小时前
7-AutoCAD-参考线、多行文字、填充命令应用
经验分享·笔记·学习·职场和发展·课程设计·制造·cad
GG.WinGel2 小时前
三元组中心问题
java·数据结构·算法·青少年编程·蓝桥杯
开开心心就好2 小时前
电脑小说阅读器,支持朗读和自定义皮肤
服务器·开发语言·javascript·算法·pdf·c#·音视频
闻缺陷则喜何志丹2 小时前
【c++20】协程与屏障
c++·算法·c++20·携程·屏障
erzong2312 小时前
Linux操作系统:线程池&踩坑修复
linux·运维·算法
alphaTao3 小时前
LeetCode 每日一题 2026/10/19-2026/10/25
算法·leetcode