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 friend's name, with some characters (possibly none) being long pressed.Example 1:
Input: name = "alex", typed = "aaleex" Output: true
Approach
Java
public class LongPressedName {public static void main(String[] args) {String name = "alex";String typed = "aaleex";System.out.println(isLongPressedName(name, typed));}static boolean isLongPressedName(String name, String typed) {int i = 0, j = 0;int n = name.length(), m = typed.length();while (i < n && j < m) {int ct = 0, cn = 0;while (j + 1 < m && typed.charAt(j + 1) == typed.charAt(j)) {ct++;j++;}while (i + 1 < n && name.charAt(i + 1) == name.charAt(i)) {cn++;i++;}if (typed.charAt(j) != name.charAt(i) || cn > ct)return false;i++;j++;}if (i == name.length() && j == typed.length() &&name.charAt(i-1) == typed.charAt(j-1))return true;return false;}}
C++
#include <bits/stdc++.h>using namespace std;bool isLongPressedName(string name, string typed){int i=0, j=0;int n=name.size(),m=typed.size();while(i<n && j<m){int ct=0, cn=0;while(typed[j+1]==typed[j]){ct++;j++;}while(name[i+1]==name[i]){cn++;i++;}if(typed[j]!=name[i] || cn>ct)return false;i++;j++;}if(i==name.size() && j==typed.size() && name[i]==typed[j])return true;return false;}int main(){string name = "alex", typed = "aaleex";if(isLongPressedName(name,typed))cout<<"true";elsecout<<"false";return 0;}
No comments:
Post a Comment