Leetcode 925. 长按键入

你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。

你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True

 

示例 1:

输入:name = "alex", typed = "aaleex"

输出:true

解释:'alex' 中的 'a' 和 'e' 被长按。

示例 2:

输入:name = "saeed", typed = "ssaaedd"

输出:false

解释:'e' 一定需要被键入两次,但在 typed 的输出中不是这样。

示例 3:

输入:name = "leelee", typed = "lleeelee"

输出:true

示例 4:

输入:name = "laiden", typed = "laiden"

输出:true

解释:长按名字中的字符并不是必要的。

 

提示:

  1. name.length <= 1000
  2. typed.length <= 1000
  3. name 和 typed 的字符都是小写字母。

 

 

**难度**: Easy

**标签**: 双指针、 字符串、


# -*- coding: utf-8 -*-
# @Author  : LG

"""
执行用时:40 ms, 在所有 Python3 提交中击败了81.82% 的用户
内存消耗:13.5 MB, 在所有 Python3 提交中击败了18.18% 的用户

解题思路:
    具体实现见代码注释
"""
class Solution:
    def isLongPressedName(self, name: str, typed: str) -> bool:
        p, q = 0, 0     #指针
        while p < len(name) and q < len(typed):
            if name[p] == typed[q]: # 如果对应位置匹配,指针同时后移,匹配下一个
                p += 1
                q += 1
            else:
                if q > 0 and typed[q-1] == typed[q]:    # 如果typed存在连击,匹配下一个
                    q += 1
                else:   # 不存在连击,返回False
                    return False
        if p >= len(name):   # name匹配完
            if q >= len(typed):  # typed 也匹配完
                return True
            else:
                while q < len(typed):   # 若typed没有匹配完,且后续连击,返回True
                    if typed[q] != typed[q-1]:  # 若不存在连击,则返回False
                        return False
                    q += 1
                return True
        else:
            return False