zoukankan      html  css  js  c++  java
  • 925. 长按键入『简单』

    题目来源于力扣(LeetCode

    一、题目

    925. 长按键入

    题目相关标签:双指针、字符串

    提示:

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

    二、解题思路

    1. 对两个字符串进行转换为字符数组的操作

    2. 遍历两个字符数组,若当前遍历的两个字符相同时,两个索引都加 1

    3. 不相同时,判断 typed 中的字符是否为长按键入的字符,即字符是否与前一个字符相同

    4. 不为长按键入的字符时,返回 false

    5. 字符串 name 的字符数组遍历结束后,若字符串 typed 的遍历未结束,则需要判断剩余的字符是否是 name字符串的最后一个字符的长按键入

    6. 最后两个字符数组都能够完全遍历,返回 true

    三、代码实现

    public static boolean isLongPressedName(String name, String typed) {
        // 长度小于 name 时,返回false
        if (typed.length() < name.length()) {
            return false;
        }
        // 相同时,不需要比较
        if (name.equals(typed)) {
            return true;
        }
        // 字符串转字符数组
        char[] names = name.toCharArray();
        char[] types = typed.toCharArray();
    
        int i = 0;
        int j = 0;
    	// 遍历两个字符数组
        while (i < names.length && j < types.length) {
            if (names[i] == types[j]) {
                i++;
                j++;
            } else if (j > 0 && types[j] == types[j - 1]) {
                // 判断当前元素是否是长按键入
                j++;
            } else {
                return false;
            }
        }
        // names遍历完了,而types后还存在元素的操作
        while (j < types.length) {
            // types 中剩余的元素是否都相同
            if (types[j] == types[j - 1]) {
                j++;
            } else {
                return false;
            }
        }
        // i与j的长度与数组长度相等
        return (i == names.length) && (j == types.length);
    }
    

    四、执行用时

    五、部分测试用例

    public static void main(String[] args) {
        String name = "alex", typed = "aaleex";  // output: true
    //    String name = "saeed", typed = "ssaaedd";  // output: false
    //    String name = "leelee", typed = "lleeelee";  // output: true
    //    String name = "laiden", typed = "laiden";  // output: true
    
        boolean result = isLongPressedName(name, typed);
        System.out.println(result);
    }
    
  • 相关阅读:
    有关base64编码算法的相关操作
    不宜多吃的十种垃圾食品
    ~ 無 淚 的 天 使 ~
    Datagrid 中添加ComboBox 的两种方法(winform)
    刀兄写的IIS管理类(C#)
    17种常用正则表达式
    正则表达式经典 (转)
    C#中Pinvoke的使用
    C#中Pinvoke的使用2
    异步操作样本
  • 原文地址:https://www.cnblogs.com/zhiyin1209/p/13189765.html
Copyright © 2011-2022 走看看