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 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron17 小时前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩18 小时前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹20 小时前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望1 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰1 天前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法
地平线开发者1 天前
J6B vio scenario sample
算法
BothSavage2 天前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法