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;
    }
}
相关推荐
孤飞4 小时前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
zjeweler5 小时前
“网安+护网”终极300多问题面试笔记-3共3-综合题型(最多)
笔记·网络安全·面试·职场和发展·护网行动
技术专家6 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
Hacker_Nightrain6 小时前
详解Selenium 和Playwright两大框架的不同之处
自动化测试·软件测试·selenium·测试工具·职场和发展
csdn_aspnet6 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
鹿角片ljp6 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
paeamecium8 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
chh5639 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮9 小时前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc
dsyyyyy11019 小时前
计数孤岛(DFS和BFS解决)
算法·深度优先·宽度优先