3330. Find the Original Typed String I #1874
-
Topics: 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 Return the total number of possible original strings that Alice might have intended to type. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the number of possible original strings Alice might have intended to type, given that she may have pressed a key for too long at most once, resulting in one or more duplicate characters in a contiguous run. The key insight is that each contiguous run of characters in the input string could be the source of the mistake, and for each run of length Approach
Let's implement this solution in PHP: 3330. Find the Original Typed String I <?php
/**
* @param String $word
* @return Integer
*/
function possibleStringCount($word) {
$n = strlen($word);
$total = 1;
$i = 0;
while ($i < $n) {
$j = $i;
while ($j < $n && $word[$j] == $word[$i]) {
$j++;
}
$len = $j - $i;
$total += $len - 1;
$i = $j;
}
return $total;
}
// Test cases
echo possibleStringCount("abbcccc") . "\n"; // Output: 5
echo possibleStringCount("abcd") . "\n"; // Output: 1
echo possibleStringCount("aaaa") . "\n"; // Output: 4
?> Explanation:
This approach efficiently counts all possible original strings by considering each contiguous run's potential contributions, leveraging the constraint that at most one mistake (a single extended run) could have occurred. The solution optimally processes the string in linear time. |
Beta Was this translation helpful? Give feedback.
We need to determine the number of possible original strings Alice might have intended to type, given that she may have pressed a key for too long at most once, resulting in one or more duplicate characters in a contiguous run. The key insight is that each contiguous run of characters in the input string could be the source of the mistake, and for each run of length
L
, there areL-1
possible original strings (since the original run could have been of any length from 1 toL-1
). Additionally, the original string without any mistake is also a possibility.Approach
Problem Analysis: The problem involves analyzing the input string to identify contiguous runs of the same character. For each s…