目錄鏈接:
力扣編程題-解法匯總_分享+記錄-CSDN博客
GitHub同步刷題項目:
https://github.com/September26/java-algorithms
原題鏈接:. - 力扣(LeetCode)
描述:
給你一個字符串?word
?,你可以向其中任何位置插入 "a"、"b" 或 "c" 任意次,返回使?word
?有效?需要插入的最少字母數(shù)。
如果字符串可以由 "abc" 串聯(lián)多次得到,則認(rèn)為該字符串?有效?。
示例 1:
輸入:word = "b" 輸出:2 解釋:在 "b" 之前插入 "a" ,在 "b" 之后插入 "c" 可以得到有效字符串 "abc" 。
示例 2:
輸入:word = "aaa" 輸出:6 解釋:在每個 "a" 之后依次插入 "b" 和 "c" 可以得到有效字符串 "abcabcabc" 。
示例 3:
輸入:word = "abc" 輸出:0 解釋:word 已經(jīng)是有效字符串,不需要進(jìn)行修改。
提示:
1 <= word.length <= 50
-
word
?僅由字母 "a"、"b" 和 "c" 組成。
解題思路:
本來想用動態(tài)規(guī)劃什么的,后來發(fā)現(xiàn),并不需要。
設(shè)置index記錄位置,取index位置的前3位,如果等于abc,則index+3,不需要插入字母;
取index位置的前2位,如果等于ab,bc,ab,則需要插入一個1個字母,index+2;文章來源:http://www.zghlxwxcb.cn/news/detail-796856.html
否則,需要插入2個字母,index+1。文章來源地址http://www.zghlxwxcb.cn/news/detail-796856.html
代碼:
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;
}
}
到了這里,關(guān)于?LeetCode解法匯總2645. 構(gòu)造有效字符串的最少插入數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!