925. Long Pressed Name(python+cpp)

题目:

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 nameand typed are lowercase letters.

解释:
判断typed是不是name手抖多按(或者没有)某些字母的结果。
双指针法,一个指针idx1指向name,另一个指针idx2指向typed,关于指针的操作中文不好解释直接看代码…
python代码:

from collections import Counter
class Solution:
    def isLongPressedName(self, name, typed):
        """
        :type name: str
        :type typed: str
        :rtype: bool
        """
        len1,len2=len(name),len(typed)
        idx1,idx2=0,0
        while idx1<len1 and idx2<len2:
            if name[idx1]==typed[idx2]:
                idx1+=1
                idx2+=1
            #不相等的话,有可能是typed重复了,操作之后idx2指向一个和前一个不一样的字母
            elif idx2>0 and typed[idx2-1]==typed[idx2]:
                idx2+=1
            #如果排除了重复问题,还是不相等的话
            else:
                return False
        #防止typed先被遍历完的情况
        return idx1==len1 

c++代码:

class Solution {
public:
    bool isLongPressedName(string name, string typed) {
        int len1=name.size();
        int len2=typed.size();
        int idx1=0,idx2=0;
        while(idx1<len1 && idx2<len2)
        {
            if(name[idx1]==typed[idx2])
            {
                idx1++;
                idx2++;
            }
            else if (idx2>0 &&typed[idx2-1]==typed[idx2])
                idx2++;
            else
                return false;
        }
        return idx1==len1;
    }
};

总结:
恩,主要是指针的操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值