LeetCode-Long Pressed Name

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/83239924

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.

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 wasn't in the typed output.

Example 3:

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

Example 4:

Input: name = "laiden", typed = "laiden"
Output: true
Explanation: It's not necessary to long press any character.

Note:

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

题意:给定一个字符串name,及一个用户敲击的字符串typed;由于用户敲击键盘中的一个字符时可能时间较长,导致一个字符出现多次;现在考虑敲击时间过长的这种情况下,判断字符串typed是否与字符串name相符;

解法:遍历字符串name,假设遍历name的当前位置为i,我们只需要从字符串typed的当前位置出发,找到与字符name.charAt(i)相等的那个字符(如果存在的话);

Java
class Solution {
    public boolean isLongPressedName(String name, String typed) {
        int index = 0;
        for (int i = 0; i < name.length(); i++) {
            while (index < typed.length() && name.charAt(i) != typed.charAt(index)) index++;
            if (index >= typed.length()) return false;
            index++;
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/83239924