本文主要是介绍LeetCode 748. 最短补全词,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:
力扣https://leetcode-cn.com/problems/shortest-completing-word/
【分析】直接用map统计字符以及出现顺序,进行比对即可。
class Solution {public class StringComporator implements Comparator<String>{@Overridepublic int compare(String o1, String o2) {if(o1.length() > o2.length()) return 1;else if(o1.length() < o2.length()) return -1;else return 0;}}public String shortestCompletingWord(String licensePlate, String[] words) {int i, v, flag;char c;Map<Character, Integer> map = new HashMap<>();for(i = 0; i < licensePlate.length(); i++){c = licensePlate.charAt(i);if(c >= 'a' && c <= 'z'){map.put(c, map.getOrDefault(c, 0) + 1);}else if(c >= 'A' && c <= 'Z'){c = (char)(c - 'A' + 'a');map.put(c, map.getOrDefault(c, 0) + 1);}}Arrays.sort(words, new StringComporator());Map<Character, Integer> tmp = new HashMap<>();for(String str: words){tmp.clear();flag = 1;for(i = 0; i < str.length(); i++){c = str.charAt(i);tmp.put(c, tmp.getOrDefault(c, 0) + 1);}for(Map.Entry<Character, Integer> entry: map.entrySet()){c = entry.getKey();v = entry.getValue();if(tmp.getOrDefault(c, 0) < v){flag = 0;break;}}if(flag == 1) return str;}return "";}
}
这篇关于LeetCode 748. 最短补全词的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!