給你一個(gè)字符串?word
?,你可以向其中任何位置插入 "a"、"b" 或 "c" 任意次,返回使?word
?有效?需要插入的最少字母數(shù)。
如果字符串可以由 "abc" 串聯(lián)多次得到,則認(rèn)為該字符串?有效?。
示例 1:
輸入:word = "b" 輸出:2 解釋?zhuān)?/strong>在 "b" 之前插入 "a" ,在 "b" 之后插入 "c" 可以得到有效字符串 "abc" 。
示例 2:
輸入:word = "aaa" 輸出:6 解釋?zhuān)?/strong>在每個(gè) "a" 之后依次插入 "b" 和 "c" 可以得到有效字符串 "abcabcabc" 。
示例 3:
輸入:word = "abc" 輸出:0 解釋?zhuān)?/strong>word 已經(jīng)是有效字符串,不需要進(jìn)行修改。
提示:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-808893.html
1 <= word.length <= 50
-
word
?僅由字母 "a"、"b" 和 "c" 組成。
題解:
直接進(jìn)行遍歷字符串的每個(gè)字符,看能拼接成abc字符串時(shí),還需要哪個(gè)字母。
注意遇到ac時(shí),只要多插個(gè)b就好。
code:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-808893.html
class Solution {
public int addMinimum(String word) {
char[] array = word.toCharArray();
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == 'a') {
if (i + 1 < array.length) {
if (array[i + 1] == 'b') {
if (i + 2 < array.length) {
if (array[i + 2] == 'c') {
i += 2;
continue;
} else {
count++;
i += 1;
continue;
}
} else {
count++;
i += 1;
continue;
}
} else if (array[i + 1] == 'c') {
count++;
i += 1;
continue;
} else {
count += 2;
}
} else {
count += 2;
}
}
if (array[i] == 'b') {
if (i + 1 < array.length) {
if (array[i + 1] == 'c') {
count++;
i++;
continue;
} else {
count += 2;
}
} else {
count += 2;
}
}
if (array[i] == 'c') {
count += 2;
}
}
return count;
}
}
到了這里,關(guān)于2645. 構(gòu)造有效字符串的最少插入數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!