748.最短补全词[简单]

144 阅读2分钟

题目

给你一个字符串 licensePlate 和一个字符串数组 words ,请你找出并返回 words 中的 最短补全词 。

补全词 是一个包含 licensePlate 中所有的字母的单词。在所有补全词中,最短的那个就是 最短补全词 。

在匹配 licensePlate 中的字母时:

忽略 licensePlate 中的 数字和空格 。 不区分大小写。 如果某个字母在 licensePlate 中出现不止一次,那么该字母在补全词中的出现次数应当一致或者更多。 例如:licensePlate = "aBc 12c",那么它的补全词应当包含字母 'a'、'b' (忽略大写)和两个 'c' 。可能的 补全词 有 "abccdef"、"caaacab" 以及 "cbca" 。

请你找出并返回 words 中的 最短补全词 。题目数据保证一定存在一个最短补全词。当有多个单词都符合最短补全词的匹配条件时取 words 中 最靠前的 那个。

提示:

  • 1 <= licensePlate.length <= 7
  • licensePlate 由数字、大小写字母或空格 ' ' 组成
  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 15
  • words[i] 由小写英文字母组成

思路

  • 将licensePlate过滤处理:过滤掉非字母,将大写字母转小写
  • 写一个match方法用于匹配是否满足
    • 基本思路类似于一个map,记录word每个字母出现的次数
    • 遍历过滤处理后的licensePlate的每个字母,对上面的map值做减一操作,如果为0,则不符合。
  • 对于匹配的判断长度是不是变小:变小重新赋值

代码

public class Lt748 {
    public String shortestCompletingWord(String licensePlate, String[] words) {
        StringBuilder lp = new StringBuilder();
        for (int i = 0; i < licensePlate.length(); i++) {
            char c = licensePlate.charAt(i);
            if (Character.isLetter(c)) {
                lp.append(Character.toLowerCase(c));
            }
        }

        String result = null;
        int min = Integer.MAX_VALUE;
        for (String word : words) {
            if (match(lp.toString(), word) && word.length() < min) {
                result = word;
                min = word.length();
            }
        }
        return result;
    }

    public boolean match(String lp, String word) {
        int[] wordCounts = new int[26];
        for (int i = 0; i < word.length(); i++) {
            wordCounts[word.charAt(i)-'a'] += 1;
        }

        for (int i = 0; i < lp.length(); i++) {
            if (wordCounts[lp.charAt(i)-'a']-- <= 0) {
                return false;
            }
        }
        return true;
    }
}