LeetCode - 748. 最短补全词

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

题目条件

题目大意:

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

  1. class Solution {
  2. public String shortestCompletingWord(String licensePlate, String[] words) {
  3. int[] array1 = new int[26]; // 数组下标对应着字符,下标所对应的值 对应是 字符的个数/ 出现的次数
  4. for(int i =0;i<licensePlate.length();i++){// 遍历 licensePlate 字符串
  5. char ch = licensePlate.charAt(i);// 获取 字符串当中字符
  6. if(Character.isLetter(ch)){// Character 的 isLetter 方法 是判断字符数据 是否是 字母
  7. // 是,就返回true,否,则返回 false
  8. array1[Character.toLowerCase(ch) - 'a']++;// 记录 每个字母字符 的 出现次数 / 个数
  9. }
  10. }
  11. int index = -1;// 为 后面 比较最短补全词,做准备
  12. for(int i = 0; i<words.length;i++){// 获取words中 字符串元素
  13. int[] array2 = new int[26];//
  14. for(int j = 0 ;j< words[i].length();j++){// 获取words数组 的 字符串元素 中 字符
  15. char ch = words[i].charAt(j);// 获取 当前字符串中 字母
  16. array2[ch-'a']++;// 计算当前 字符串元素中 每个字母的 个数/出现次数
  17. }
  18. boolean b = true;// 判断 licensePlate 字符串 提取出 字母 是否都在 words 某一个元素中
  19. for(int n = 0;n<26;n++){
  20. if(array1[n]>array2[n]){
  21. b = false;
  22. break;
  23. }
  24. }
  25. // 记录最短补全词的下标
  26. // 注意逻辑或 后面的 两个条件是不能互换的,如果你互换了,那么在第一次找到满足条件的元素时,
  27. // 此时 index还是 -1,这时 words[index].length() 就会引出 越界异常了
  28. if(b && (index<0 || words[i].length() < words[index].length())){
  29. index = i;
  30. }
  31. }
  32. return words[index];
  33. }
  34. }

图解

相关文章