925. Long Pressed Name

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

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.

Constraints:

  • 1 <= name.length <= 1000

  • 1 <= typed.length <= 1000

  • The characters of name and typed are lowercase letters.

给定name和typed两个字符串,问typed是否由name中每个字符出现一次或数次拼接而成。两个指针i, j分别指向name和typed的起始。匹配时就一起往前走,不同时检查typed[j]是否和typed[j-1]相同,相同则意味着是重复,向前移动j,否则不匹配。

代码参考了lee251。

class Solution:
    def isLongPressedName(self, name: str, typed: str) -> bool:
        i = 0
        for j in range(len(typed)):
            if i < len(name) and name[i] == typed[j]:
                i += 1
            elif j == 0 or typed[j] != typed[j - 1]:
                return False
        return i == len(name)

Last updated