Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
With at most one long keypress, only one run of equal characters can be shortened. A run of length r permits r - 1 shorter positive lengths. The unchanged word is one additional possibility shared by all runs.
Approach
Scan adjacent character pairs and count how many consecutive equalities occur within the current run. When the character changes, add that count to the answer and reset it. After the scan, add the final run's count and one for the unchanged word.
Each shorter run length produces a distinct original word, and shortening different runs changes different positions in the run sequence, so these possibilities do not overlap. Adding the unchanged case only once avoids counting it separately for every run. Single-character runs contribute zero additional choices.
class Solution:
def possibleStringCount(self, word: str) -> int:
n = len(word)
res = 0
r = 0
for i in range(1, n):
if word[i] == word[i - 1]:
r += 1
else:
res += r
r = 0
return res + r + 1Complexity analysis
Let n = word.length. Time: O(n). Auxiliary space: O(1).
