Find the Original Typed String I Problem
Description
LeetCode Problem 3330.
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 <= 100wordconsists only of lowercase English letters.
Solution
Approach: Direct Traversal
Alice may have held a key too long at most once, which turns a single character into a run of that character. If no two adjacent characters are equal, the only possibility is word itself. Each pair of equal neighbours gives one extra possibility: the run containing it could have been one character shorter. For example "abbc" can come from "abbc" or "abc".
So scan the string, count the adjacent equal pairs k, and return k + 1.
Complexity: O(n) time and O(1) space, where n is the length of the word.
class Solution:
def possibleStringCount(self, word: str) -> int:
return 1 + sum(x == y for x, y in zip(word, word[1:]))