Long Pressed Name

Your friend is using the keyboard to enter his name name. Occasionally, when the character c is being typed, the key may be long-pressed, and the character may be input 1 or more times.

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

Example

Input: name = "alex", typed = "aaleex" Output: true Explanation: 'a' and 'e' in 'alex' are long-pressed.
Input: name = "saeed", typed = "ssaaedd" Output: false Explanation: 'e' needs to be typed twice, but it's not in the output of 'typed'.
Input: name = "leelee", typed = "lleeelee" Output: true
Input: name = "laiden", typed = "laiden" Output: true Explanation: Long pressing characters in the name is not necessary.

Solution

/**
 * @param {string} name
 * @param {string} typed
 * @return {boolean}
 */
var isLongPressedName = function(name, typed) {
    if(name === typed) return true;
    var i=0, k=0;
    var n = name.length;
    for(; i<n;){
        let char = name[i];
        if(name[i] !== typed[k]) return false;
        let catchedI = i;
        let catchedK = k;
        while(name[++i] === char);
        while(typed[++k] === char);
        if(i - catchedI > k - catchedK) return false;
    }
    if(i !== n || k !== typed.length) return false;
    return true;
};

Idea

Utilizing the strategy of double pointers, set a pointer for each of the two strings, and traverse the two strings, dealing with repeated characters so that the pointer always points to the next different character. Judge whether the input has reached the sufficient quantity, and finally determine whether the strings are completely traversed. First, judge whether the strings are the same, and if so, return true directly. Then define two pointers i and k as pointers for traversing the name and typed strings, then define n as the length of the name string, and then define a loop. Here I used for, but actually using while is better. Then get the current character and judge the characters pointed to by the two pointers. If they are different, return false directly. Cache the values of the two pointers, and then use while to ensure that the two pointers always point to the first character different from the current character. Then judge if the current character in typed has a quantity greater than or equal to the current character in name, according to the requirement of the problem, the quantity of the current character value in typed needs to be greater than or equal to the quantity of the current character value in name. If it does not meet the condition, return false directly. Then judge whether both pointers have completed traversal. If they have not completed traversal, return false. Finally, if all conditions are met, return true.

Daily Topic

https://github.com/WindrunnerMax/EveryDay

Reference

https://leetcode-cn.com/problems/long-pressed-name/