cocobear9  
一枚普通的zisuer(lll¬ω¬),努力每天多学一点点

如果单词列表(words)中的一个单词包含牌照(licensePlate)中所有的字母,那么我们称之为完整词。在所有完整词中,最短的单词我们称之为最短完整词。

单词在匹配牌照中的字母时不区分大小写,比如牌照中的 "P" 依然可以匹配单词中的 "p" 字母。

我们保证一定存在一个最短完整词。当有多个单词都符合最短完整词的匹配条件时取单词列表中最靠前的一个。

牌照中可能包含多个相同的字符,比如说:对于牌照 "PP",单词 "pair" 无法匹配,但是 "supper" 可以匹配

输入:licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
输出:"steps"
说明:最短完整词应该包括 "s"、"p"、"s" 以及 "t"。对于 "step" 它只包含一个 "s" 所以它不符合条件。同时在匹配过程中我们忽略牌照中的大小写。

链接:https://leetcode-cn.com/problems/shortest-completing-word

常规思路

class Solution {
    public String shortestCompletingWord(String licensePlate, String[] words) {
        Map<Character,Integer> map = new HashMap<>();
        String license =licensePlate.toLowerCase();
        for(char c:license.toCharArray()) {
            if('a'<=c && c<='z') {
                map.put(c,map.getOrDefault(c, 0)+1);
            }
        }
        int flag =0;
        String tmpMins ="";
        Set<Character> set = map.keySet();//s p t
        for(int i=0;i<words.length;i++) {
            boolean b = true;
            Map<Character,Integer> word = new HashMap<>();
            for(char ch:words[i].toCharArray()) {
                word.put(ch, word.getOrDefault(ch, 0)+1);
            }
            for(char c : set) {
                if(!word.containsKey(c) || word.get(c)<map.get(c)) {
                    b=false;
                    break;
                }
            }
            if(b) {
                if(flag==0) {
                    tmpMins=words[i];
                    flag=1;
                } 
                if(tmpMins.length() > words[i].length() ) {
                    tmpMins = words[i];
                }
            }
            word.clear();
        }
        return tmpMins ;
    }
}

 

posted on 2020-05-15 22:30  cocobear9  阅读(180)  评论(0)    收藏  举报