zoukankan      html  css  js  c++  java
  • [LeetCode] 925. Long Pressed Name

    Your friend is typing his name into a keyboard.  Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.

    You examine the typed characters of the keyboard.  Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.

    Example 1:

    Input: name = "alex", typed = "aaleex"
    Output: true
    Explanation: 'a' and 'e' in 'alex' were long pressed.
    

    Example 2:

    Input: name = "saeed", typed = "ssaaedd"
    Output: false
    Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.
    

    Example 3:

    Input: name = "leelee", typed = "lleeelee"
    Output: true
    

    Example 4:

    Input: name = "laiden", typed = "laiden"
    Output: true
    Explanation: It's not necessary to long press any character.

    Constraints:

    • 1 <= name.length <= 1000
    • 1 <= typed.length <= 1000
    • The characters of name and typed are lowercase letters.

    你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。

    你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。

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

    思路是two pointer,一个i指针走name,一个j指针走typed。当没有遍历完name的时候,如果两边的字符是一样的,则往前走;如果两边字符不一样,则需要判断

    • j是否在0的位置上,如果是,那说明第一个字母就对不上,直接return false
    • j如果不在0的位置上,则判断j是否跟j - 1位置上的字母相等,如是,则有可能是重复字母

    时间O(n)

    空间O(1)

    Java实现

     1 class Solution {
     2     public boolean isLongPressedName(String name, String typed) {
     3         int i = 0;
     4         int m = name.length();
     5         int n = typed.length();
     6         for (int j = 0; j < n; j++) {
     7             if (i < m && name.charAt(i) == typed.charAt(j)) {
     8                 i++;
     9             } else if (j == 0 || typed.charAt(j) != typed.charAt(j - 1)) {
    10                 return false;
    11             }
    12         }
    13         return i == m;
    14     }
    15 }

    LeetCode 题目总结

  • 相关阅读:
    nodejs使用superagent写爬虫dns超时
    react部署nginx刷新路由404
    ubuntu安装mongodb添加账户以及远程连接
    laravel使用layui富文本编辑器layedit上传图片419解决办法
    编写前端统计网页流量,来源,停留时间等
    laravel模版共用数据解决方法
    解决MySQL导入中文乱码
    yii2 jui DatePicker widget 设置显示默认时间
    装饰器
    python函数计时器(通过装饰器实现)
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13850015.html
Copyright © 2011-2022 走看看