你的朋友正在使用键盘输入他的名字 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;
}
}

最新文章

  1. mybatis- spring 批量实现数据导入数据库
  2. windows7设置开机启动方式
  3. 【转载】App.config/Web.config 中特殊字符的处理
  4. 激活PHPStorm 2016.3
  5. ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
  6. XMl入门介绍及php操作XML
  7. Android判断App是否在前台运行(转)
  8. 如何申请TexturePacker注册码
  9. hdu Big Number 求一个数的位数
  10. C语言的本质(17)——回调函数
  11. Android工程师面试准备知识点
  12. jquery-scrollstop
  13. 9.2.1、Libgdx的输入处理之轮询
  14. 单链表&amp;双链表的头插入&amp;尾插入
  15. js插件ztree使用
  16. LR两种录制模式的区别
  17. 释放锁标记只有在Synchronized代码结束或者调用wait()。
  18. hdu 1754 I Hate It (单点修改+区间最值+裸题)
  19. Ex 6_16 旧货销售问题_第七次作业
  20. 【设计模式】——工厂方法FactoryMethod

热门文章

  1. CSAPP: 位操作实现基本运算
  2. angular之模块开发二
  3. mac本地安装单机hadoop--学习笔记
  4. 元祖tuple
  5. 设计模式(十二)Decorator模式
  6. django-模板之comment标签(六)
  7. transform-origin盒子旋转位置
  8. FPGA时序约束理解记录
  9. 第二十五章 system v消息队列(一)
  10. 【IT教程-Oracle】尚观Oracle白金级入门教程