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

题解

采用双指针方式遍历判断单个字符是否相等

当单个字符相等时,两个指针向后进一位

当单个字符不相等时,判断 typed 指针的前一位是否与当前相同,如果相同则 typed 指针 向后进一位,不相同就不匹配返回 false

当其中一个指针走完后,判断 typed 指针是否走完,没走完遍历对比 name 字符串的最后一位

最后再判断 name 指针是否在最后一位

  1. /**
  2. * @param {string} name
  3. * @param {string} typed
  4. * @return {boolean}
  5. */
  6. var isLongPressedName = function(name, typed) {
  7. let i = 0
  8. let j = 0
  9. let l1 = name.length
  10. let l2 = typed.length
  11. if (l2 < l1) {
  12. return false
  13. }
  14. while(i < l1 && j < l2) {
  15. if (name[i] === typed[j]) {
  16. i++
  17. j++
  18. } else if (typed[j] === typed[j - 1]) {
  19. j++
  20. } else {
  21. return false
  22. }
  23. }
  24. while(j < l2) {
  25. if (typed[j] === name[name.length - 1]) {
  26. j++
  27. } else {
  28. return false
  29. }
  30. }
  31. return i === l1
  32. };

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/long-pressed-name
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。