zoukankan      html  css  js  c++  java
  • 力扣(LeetCode)长按键入 个人题解

    你的朋友正在使用键盘输入他的名字 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 的字符都是小写字母。

    算法思想是显而易见的。两个指针方便指向两个字符串,并比较对应位置是否匹配。

    当对应位置不匹配时,移动typed的指针指向下一个,判断是否和typed最后匹配的那一位相同,如果相同,则继续前进,直到进入下一个匹配位置。如果不相同,则返回false。

    这里要注意到一种特例,那就是typed的长度必定大于name,而且第一位和最后一位必须相同,这样可以为我们节省一点时间。

    代码如下:

    class Solution {
        public boolean isLongPressedName(String name, String typed) {
            if (name.equals(typed))
                return true;
            if (name.length() > typed.length() || name.charAt(0) != typed.charAt(0)
                    || name.charAt(name.length() - 1) != typed.charAt(typed.length() - 1))
                return false;
            int pre = 0, index1 = 0, index2 = 0;
            while (index1 < name.length() && index2 < typed.length()) {
                if (name.charAt(index1) == typed.charAt(index2)) {
                    pre = index1;
                    index1++;
                    index2++;
    
                } else if (name.charAt(pre) == typed.charAt(index2)) {
                    index2++;
                } else {
                    return false;
                }
    
            }
            return true;
        }
    }
  • 相关阅读:
    NHibernate之映射文件配置说明(转载3)
    NHibernate之映射文件配置说明(转载2)
    NHibernate之映射文件配置说明(转载1)
    NHibernate+NUnit (VS2012+SQL Server2008) (转)
    ASP.NET MVC全局观
    使用Razor来进行页面布局
    视图引擎输出字符串
    @Html.Partial,@Html.Action,@Html.RenderPartial,@Html.RenderAction
    Html.Action和Html.RederAction来创建子视图
    从客户端检测到有潜在危险的Request.Form值
  • 原文地址:https://www.cnblogs.com/axiangcoding/p/10388552.html
Copyright © 2011-2022 走看看