[LeetCode] 3330. Find the Original Typed String I
Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and may press a key for too long, resulting in a character being typed multiple times.
Although Alice tried to focus on her typing, she is aware that she may still have done this at most once.
You are given a string word, which represents the final output displayed on Alice's screen.
Return the total number of possible original strings that Alice might have intended to type.
Example 1:
Input: word = "abbcccc"
Output: 5
Explanation:
The possible strings are: "abbcccc", "abbccc", "abbcc", "abbc", and "abcccc".
Example 2:
Input: word = "abcd"
Output: 1
Explanation:
The only possible string is "abcd".
Example 3:
Input: word = "aaaa"
Output: 4
Constraints:
1 <= word.length <= 100
word consists only of lowercase English letters.
找到初始輸入字符串 I。
Alice 正在她的電腦上輸入一個字符串。但是她打字技術比較笨拙,她 可能 在一個按鍵上按太久,導致一個字符被輸入 多次 。盡管 Alice 盡可能集中注意力,她仍然可能會犯錯 至多 一次。
給你一個字符串 word ,它表示 最終 顯示在 Alice 顯示屏上的結果。
請你返回 Alice 一開始可能想要輸入字符串的總方案數。
思路
這道題不涉及算法,注意觀察字符串的規律。如果相鄰的字符相同,那么第二個字母就有可能是一次重復的輸入。所以我們可以遍歷 input 字符串,如果當前字母跟前一個字母不一樣,則說明沒有犯錯;如果跟前一個字母一樣,那么第二個字母就有可能是因為犯錯而輸入的,則計數加一。
復雜度
時間O(n)
空間O(1)
代碼
Java實現
class Solution {
public int possibleStringCount(String word) {
int count = 1;
int n = word.length();
for (int i = 1; i < n; i++) {
if (word.charAt(i) == word.charAt(i - 1)) {
count++;
}
}
return count;
}
}

浙公網安備 33010602011771號