拓撲排序——外星文字典114
阿新 • • 發佈:2021-12-22
外星人字典
題目:外星文字典
給定一個字串列表words
,作為這門語言的詞典,words
中的字串已經按這門新語言的字母順序進行了排序。
示例 1:
輸入:words = ["wrt","wrf","er","ett","rftt"]
輸出:"wertf"
示例2:
輸入:words=["ac","ab","zc","zb"]
輸出:acbz
思路:
1. 根據詞典,排序: 如["wrf", "wrf"]中,r的詞典排序小於f。
2. 如果字元在詞典中沒有順序,則按照正常字母排序:如["ac","ed"], c和d沒有順序,則按正常順序排序,即c<d
3.如果字串1和字串2的最小公共字串都相同,若前字串的長度大於後字串的長度,則不符合要求:如["abc","ab"]顯然不符合排序規則,返回'''';
題解
求按詞典規則的拓撲排序
class Solution { public String alienOrder(String[] words) { Queue<Character> queue = new PriorityQueue<>(); Map<Character, List<Character>> map = new HashMap<>(); int book[]=new int[26]; Arrays.fill(book, -1); //所有節點入度設為0 for (int i = 0; i < words.length; i++) { String str = words[i]; for (int j = 0; j < str.length(); j++) { book[str.charAt(j)-'a']=0; } } //根據詞典生成拓撲圖 for (int i = 0; i < words.length - 1; i++) { int index = 0; while (index < words[i].length() && index < words[i + 1].length()) { if (words[i].charAt(index) != words[i + 1].charAt(index)) { map.putIfAbsent(words[i].charAt(index), new ArrayList<>()); if(!map.get(words[i].charAt(index)).contains(words[i+1].charAt(index))) { map.get(words[i].charAt(index)).add(words[i + 1].charAt(index)); book[words[i+1].charAt(index)-'a']++; } break; } index++; } if (index == Math.min(words[i].length(), words[i + 1].length())) { if (words[i].length() > words[i + 1].length()) { return ""; } } } //節點為0,則入佇列 int sum=0; for(int i=0;i< book.length;i++) { if(book[i]==0) queue.add((char) (i+'a')); if(book[i]!=0) sum++; } //計算拓撲排序 int index=0; char res[]=new char[sum]; while (!queue.isEmpty()) { char temp=queue.poll(); res[index++]=temp; if(map.get(temp)!=null) { for(char nigb: map.get(temp)) { book[nigb-'a']--; if(book[nigb-'a']==0) queue.add(nigb); } } } return index==sum?new String(res):""; } }
演算法小白,歡迎指教。