leetcode【每日一题】925. 长按键入 Java

it2023-12-14  69

题干

你的朋友正在使用键盘输入他的名字 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 解释:长按名字中的字符并不是必要的。

提示:

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

来源:力扣(LeetCode)

想法

双指针模拟 分别指向name里已经匹配到的位置和typed里边正在比较的位置 如果

(1)name.charAt(i)==typed.charAt(j)

证明此位置匹配,i++,j++

(2)typed.charAt(j-1)==typed.charAt(j)

此位置的字符在name里已经比较过,只是typed的重复

(3)其他情况

不匹配 ,可以直接返回false

java代码

class Solution { public boolean isLongPressedName(String name, String typed) { int i=0,j=0; while(j<typed.length()){ if(i<name.length()&&name.charAt(i)==typed.charAt(j)){ i++; j++; } else if(j>0&&typed.charAt(j-1)==typed.charAt(j)){ j++; } else { return false; } } return i==name.length(); } }

我的leetcode都已经上传到我的githttps://github.com/ragezor/leetcode

最新回复(0)