748. Shortest Completing Word

Easy
属于没什么算法那种题,逻辑简单,注意下细节就没事了。

class Solution {
    public String shortestCompletingWord(String licensePlate, String[] words) {
        String letters = licensePlate.replaceAll("[^A-Za-z]+","").toLowerCase();
        Map<Character, Integer> map = new HashMap<>();
        for (char c : letters.toCharArray()){
            if (!map.containsKey(c)){
                map.put(c, 1);
            } else {
                map.put(c, map.get(c) + 1);
            }
        }
        //System.out.println(map.entrySet());
        Arrays.sort(words, lenComparator);
        for (String word : words){
            boolean valid = true;
            char[] chs = word.toCharArray();
            Map<Character, Integer> hash = new HashMap<>();
            for (char ch : chs){
                if (!hash.containsKey(ch)){
                    hash.put(ch, 1);
                } else {
                    hash.put(ch, hash.get(ch) + 1);
                }
            }
            //System.out.println(hash.entrySet());
            for (char c : map.keySet()){
                if (hash.containsKey(c) && hash.get(c) >= map.get(c)){
                    continue;
                } else {
                    valid = false;
                    break;
                }
            }
            if (valid){
                return word;    
            } else {
                continue;
            }
            
        }
        return "";
    }
    
    private Comparator<String> lenComparator = new Comparator<String>(){
        public int compare(String s1, String s2){
            return s1.length() - s2.length();
        }
    };
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/f113136cf97c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞