LeetCode - 748. 最短补全词

x33g5p2x  于2021-12-11 转载在 其他  
字(1.0k)|赞(0)|评价(0)|浏览(171)

题目条件

题目大意:

先上代码,一上来看图解,怕你们不了解。我的图解,需要你们先看一遍程序有个印象。

class Solution {
    public String shortestCompletingWord(String licensePlate, String[] words) {
        int[] array1 = new int[26]; // 数组下标对应着字符,下标所对应的值 对应是 字符的个数/ 出现的次数
        for(int i =0;i<licensePlate.length();i++){// 遍历 licensePlate 字符串
            char ch = licensePlate.charAt(i);// 获取 字符串当中字符
            if(Character.isLetter(ch)){// Character 的 isLetter 方法 是判断字符数据 是否是 字母
                // 是,就返回true,否,则返回 false

                array1[Character.toLowerCase(ch) - 'a']++;// 记录 每个字母字符 的 出现次数 / 个数
            }
        }
        int index = -1;// 为 后面 比较最短补全词,做准备
        for(int i = 0; i<words.length;i++){// 获取words中 字符串元素
            int[] array2 = new int[26];//
            for(int j = 0 ;j< words[i].length();j++){// 获取words数组 的 字符串元素 中 字符 
                    char ch = words[i].charAt(j);// 获取 当前字符串中 字母
                    array2[ch-'a']++;// 计算当前 字符串元素中 每个字母的 个数/出现次数
                }

                boolean b = true;// 判断 licensePlate 字符串 提取出 字母 是否都在 words 某一个元素中 
                for(int n = 0;n<26;n++){
                    if(array1[n]>array2[n]){
                        b = false;
                        break;
                    }              
                }
                // 记录最短补全词的下标
                // 注意逻辑或 后面的 两个条件是不能互换的,如果你互换了,那么在第一次找到满足条件的元素时,
                // 此时 index还是 -1,这时 words[index].length() 就会引出 越界异常了
                if(b && (index<0 || words[i].length() < words[index].length())){
                    index = i;
                }
            }
        return words[index];
    }
}

图解

相关文章