Long Pressed Name
The problem requires us to check if the string typed
could be formed from the string name
by possibly long pressing some keys. A key is long pressed if it is repeated one or more times consecutively.
Approach:
- Initialize Pointers: We will initialize two pointers, one for each string.
- Iterate Through Strings: We will iterate through both strings using the pointers, checking if the characters match.
- Handle Long Pressed Characters: If a character in
typed
is the same as the previous character, we need to check if it matches the current character inname
. If not, it could be a long-pressed character. - Final Check: We should ensure that we have checked all characters in
name
and handled the long-pressed characters intyped
.
Code:
Here’s the code implementing the above approach:
|
|
Explanation:
- The while loop iterates through
typed
, and the pointersi
andj
are used to traversename
andtyped
, respectively. - If the characters at the current pointers match, both pointers are moved forward.
- If the current character in
typed
is the same as the previous character but doesn’t match the current character inname
, it’s considered a long press, and only the pointer intyped
is moved forward. - If a character in
typed
doesn’t meet any of the above conditions, it meanstyped
cannot be formed fromname
, andFalse
is returned. - After the loop, we ensure that all characters in
name
have been checked.
Example:
- For
name = "alex"
andtyped = "aaleex"
, the function returnsTrue
, as ‘a’ and ’e’ are long pressed. - For
name = "saeed"
andtyped = "ssaaedd"
, the function returnsFalse
, as there is no second ’e’ in the typed string.
This code takes care of the constraints and efficiently checks if the typed
string could have been formed from the name
string by long pressing some keys.