词频统计简单 LeetCode748. 最短补全词

748. 最短补全词

描述

给你一个字符串 licensePlate 和一个字符串数组 words ,请你找出并返回 words 中的 最短补全词 。
补全词 是一个包含 licensePlate 中所有的字母的单词。在所有补全词中,最短的那个就是 最短补全词 。
在匹配 licensePlate 中的字母时:
忽略 licensePlate 中的 数字和空格 。
不区分大小写。
如果某个字母在 licensePlate 中出现不止一次,那么该字母在补全词中的出现次数应当一致或者更多。
例如:licensePlate = “aBc 12c”,那么它的补全词应当包含字母 ‘a’、‘b’ (忽略大写)和两个 ‘c’ 。可能的 补全词 有 “abccdef”、“caaacab” 以及 “cbca” 。
请你找出并返回 words 中的 最短补全词 。题目数据保证一定存在一个最短补全词。当有多个单词都符合最短补全词的匹配条件时取 words 中 最靠前的 那个。

分析

分别计算出licensePlate的词频统计和words中字符串的词频统计,然后比较是否满足“最短补全词”。

class Solution {
    
    
    public String shortestCompletingWord(String licensePlate, String[] words) {
    
    
        int[] lic = getCnt(licensePlate);
        int min = Integer.MAX_VALUE;
        String ans = "";
        for(String str : words){
    
    
            int[] word = getCnt(str);
            int i = 0;
            for(; i < 26; i++){
    
    
                if(word[i] < lic[i]){
    
    
                    break;
                }
            }
            if(i == 26 && str.length() < min){
    
    
                ans = str;
                min = str.length();
            }
        }
        return ans ;
    }

    public int[] getCnt(String str){
    
    
        int[] chaCnt = new int[26];
        for(int i = 0; i < str.length(); i++){
    
    
            char tmp = str.charAt(i);
            if(tmp <= 'Z' && tmp >= 'A'){
    
    
                chaCnt[tmp-'A']++;
            }
            if(tmp >= 'a' && tmp <= 'z'){
    
    
                chaCnt[tmp-'a']++;
            }
        }
        return chaCnt;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43260719/article/details/121865449
今日推荐