力扣(LeetCode)长按键入 个人题解
2024-08-28 12:57:14
你的朋友正在使用键盘输入他的名字 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
的字符都是小写字母。
算法思想是显而易见的。两个指针方便指向两个字符串,并比较对应位置是否匹配。
当对应位置不匹配时,移动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;
}
}
最新文章
- mybatis- spring 批量实现数据导入数据库
- windows7设置开机启动方式
- 【转载】App.config/Web.config 中特殊字符的处理
- 激活PHPStorm 2016.3
- ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
- XMl入门介绍及php操作XML
- Android判断App是否在前台运行(转)
- 如何申请TexturePacker注册码
- hdu Big Number 求一个数的位数
- C语言的本质(17)——回调函数
- Android工程师面试准备知识点
- jquery-scrollstop
- 9.2.1、Libgdx的输入处理之轮询
- 单链表&;双链表的头插入&;尾插入
- js插件ztree使用
- LR两种录制模式的区别
- 释放锁标记只有在Synchronized代码结束或者调用wait()。
- hdu 1754 I Hate It (单点修改+区间最值+裸题)
- Ex 6_16 旧货销售问题_第七次作业
- 【设计模式】——工厂方法FactoryMethod