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;
    }
}
相关推荐
NAGNIP13 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队14 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja19 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下19 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶19 小时前
算法 --- 字符串
算法
博笙困了19 小时前
AcWing学习——差分
c++·算法
NAGNIP19 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP19 小时前
大模型微调框架之LLaMA Factory
算法
echoarts19 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客19 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法