(Js) leetcode 925. Long press to enter

topic:

Your friend is using the keyboard to enter his name name. Occasionally, when typing the character c, the key may be long pressed, and the character may be entered one or more times.

You will check the typed characters entered on the keyboard. If it corresponds to your friend's name (some characters may be long-pressed), then return True.

Example 1:

Input: name = "alex", typed = "aaleex"
Output: true
Explanation: The'a' and'e' in'alex ' are long pressed.
Example 2:

Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation:'e' must be typed twice, but this is not the case in typed output.
Example 3:

Input: name = "leelee", typed = "lleeelee"
Output: true
Example 4:

Input: name = "laiden", typed = "laiden"
Output: true
Explanation: Long-pressing the characters in the name is not necessary.

prompt:

name.length <= 1000
typed.length <= 1000
The characters of name and typed are all lowercase letters.

Ideas:

Use dual pointers

Code:

/**
 * @param {string} name
 * @param {string} typed
 * @return {boolean}
 */
var isLongPressedName = function(name, typed) {
    const n = name.length, m = typed.length;
    let i = 0, j = 0;
    while (j < m) {
        if (i < n && name[i] === typed[j]) {
            i++;
            j++;
        } else if (j > 0 && typed[j] === typed[j - 1]) {
            j++;
        } else {
            return false;
        }
    }
    return i === n;
};

operation result:

Guess you like

Origin blog.csdn.net/M_Eve/article/details/113705434