DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Long Pressed Name

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 and typed consist of only lowercase English letters.

SOLUTION:

class Solution:
    def getRLE(self, string):
        n = len(string)
        i = 0
        op = []
        while i <= n - 1:
            ctr = 1
            while i < n - 1 and string[i] == string[i + 1]:
                ctr += 1
                i += 1
            i += 1
            op.append((string[i - 1], ctr))
        return op

    def isLongPressedName(self, name: str, typed: str) -> bool:
        namelist = self.getRLE(name)
        typedlist = self.getRLE(typed)
        m = len(namelist) 
        n = len(typedlist)
        if m == n:
            for i in range(m):
                if namelist[i][0] != typedlist[i][0]:
                    return False
                if namelist[i][1] > typedlist[i][1]:
                    return False
            return True
        return False
Enter fullscreen mode Exit fullscreen mode

Top comments (0)