925. Long Pressed Name(Solution || Leetcode easy || Java)
Your friend is typing his name
into a keyboard. Sometimes, when typing a character c
, the key might get long pressed, and the character will be typed 1 or more times.
You examine the typed
characters of the keyboard. Return True
if it is possible that it was your friends name, with some characters (possibly none) being long pressed.
Example 1:
Input: name = "alex", typed = "aaleex"
Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.
Example 2:
Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation: 'e' must have been pressed twice, but it was not in the typed output.
Constraints:
1 <= name.length, typed.length <= 1000
name
andtyped
consist of only lowercase English letters.
SOLUTION:
class Solution {
public boolean isLongPressedName(String name, String typed) {
if(name.length() > typed.length()){
return false;
}
//initialize index to iterate over the strings
int i = 0;
int j = 0;
int nLen = name.length();
int tLen = typed.length();
while(i < nLen && j < tLen){
char ch = name.charAt(i);
if(name.charAt(i) != typed.charAt(j)){
return false;
}
i++; j++;
int nameCharLen = 0;
int typedCharLen = 0;
while(i < nLen && ch == name.charAt(i)){
i++;
nameCharLen++;
}
while(j < tLen && ch == typed.charAt(j)){
j++;
typedCharLen++;
}
if(nameCharLen > typedCharLen){
return false;
}
}
if(i == nLen && j == tLen){
return true;
}
return false;
}
}
Runtime: 1 ms, faster than 92.23% of Java online submissions for Long Pressed Name.
Memory Usage: 40.4 MB, less than 88.77% of Java online submissions for Long Pressed Name
Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.