LeetCode: Long press to enter

Title description

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.

Ideas

  • The general meaning of the question is: to determine whether there are certain characters in the input name because the hand shakes the input repeatedly
  • The name of the friend is name, and the name entered by the friend is typed
  • Through charAt(), you can get the character of the specified subscript in the string
  • name.charAt(i) represents the character in name, typed.charAt(j) represents the character in typed
  • Comparing from the beginning, situation ① If name.charAt(i)==typed.charAt(j), then i and j are both ++ , comparing the next character is equivalent to two pointers
  • ② situation if not equal, then it is more typed.charAt (j) is equal to typed.charAt (J-1) , if they are equal, then re-enter the tremor is, only j ++ can
  • Case ③, both cases are not met, this shows that the current character is neither a character name should appear in the current order, nor is it to re-enter the character to return false to

Code

class Solution {
    public boolean isLongPressedName(String name, String typed) {
        int i=0;
        int j=0;
        while(j<typed.length()){
            if(i<name.length()&&name.charAt(i)==typed.charAt(j)){
                i++;
                j++;
            }else if(j>0&&typed.charAt(j)==typed.charAt(j-1)){
                j++;
            }else{
                return false;
            }
        }
        return i==name.length();
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_43939602/article/details/114122927