c# leetcode 925长按键入(双指针)

六眼飞鱼酱① 提交于 2019-12-26 06:56:22

 title:

你的朋友正在使用键盘输入他的名字 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
解释:长按名字中的字符并不是必要的。 
链接:https://leetcode-cn.com/problems/long-pressed-name 

thinking:  两个字符串的都指针++,然后判断第二个字符串的指针和第一个字符串的上一个是否相等***

code:

        public bool IsLongPressedName(string name, string typed)
        {
            int index = 0, int indexTyped = 0
            while (indexTyped < typed.Length)
            {
                //  match current
                if (index < name.Length && name[index] == typed[indexTyped])
                {
                    index++;
                    indexTyped++;
                }
                // match previous one
                else if (index > 0 && name[index - 1] == typed[indexTyped])
                {
                    ++indexTyped;
                }
                else
                {
                    return false;
                }
            }

            // make sure that original string is iterated completely. 
            return index == name.Length;
         }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!