925. Long Pressed Name

1. Description

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.

2. Example

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.

3. Constraints

  • 1 <= name.length, typed.length <= 1000
  • name and typed consist of only lowercase English letters.

4. Solutions

My Accepted Solution

m = name.size(), n = typed.size()
Time complexity: O(m + n)
Space complexity: O(1)

class Solution {
public:
    bool isLongPressedName(const string &name, const string &typed) {
        int i = 0, j = 0;
        for (int i_letters = 0, j_letters = 0; i < name.size() && j < typed.size();) {
            char letter_i = name[i];
            for (i_letters = 0; i < name.size() && name[i] == letter_i; ++i) {
                ++i_letters;
            }

            char letter_j = typed[j];
            for (j_letters = 0; j < typed.size() && typed[j] == letter_j; ++j) {
                ++j_letters;
            }

            if (i_letters > j_letters || name[i - 1] != typed[j - 1]) {
                return false;
            }
        }

        return i == name.size() && j == typed.size();
    }
};
comments powered by Disqus