图基础算法(四)- 拓扑排序
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.
You are given a list of strings words
from the alien language's dictionary, where the strings in words
are sorted lexicographically by the rules of this new language.
Return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new language's rules. If there is no solution, return ""
. If there are multiple solutions, return any of them.
A string s
is lexicographically smaller than a string t
if at the first letter where they differ, the letter in s
comes before the letter in t
in the alien language. If the first min(s.length, t.length)
letters are the same, then s
is smaller if and only if s.length < t.length
.
Example 1:
Input: words = ["wrt","wrf","er","ett","rftt"] Output: "wertf"
Example 2:
Input: words = ["z","x"] Output: "zx"
Example 3:
Input: words = ["z","x","z"]
Output: ""
Explanation: The order is invalid, so return ""
.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
consists of only lowercase English letters.
class Solution { public String alienOrder(String[] words) { //1.build the graph Map> graph = new HashMap(); Map indegree = new HashMap(); for(String str:words){ for(char c:str.toCharArray()){ indegree.put(c,0); } } for(int i=0;i ){ String str1 = words[i],str2=words[i+1]; for(int j=0;j ){ if(str1.length()>str2.length() && str1.startsWith(str2)) return ""; //坑点1.["abc","ab"] 为不合法的字典,直接返回 char c1=str1.charAt(j),c2 = str2.charAt(j); if(c1!=c2){ List list = graph.getOrDefault(c1,new ArrayList()); graph.put(c1,list); list.add(c2); indegree.put(c2,indegree.getOrDefault(c2,0)+1); break; } } } //2.toplogical sort Queue queue = new LinkedList(); StringBuffer sb = new StringBuffer(""); for(char c:indegree.keySet()){ if(indegree.get(c)==0) { queue.offer(c); sb.append(c); } } while(!queue.isEmpty()){ char c = queue.poll(); for(char t:graph.getOrDefault(c,Arrays.asList())){ indegree.put(t,indegree.get(t)-1); if(indegree.get(t)==0) { queue.offer(t); sb.append(t); } } } return sb.length()==indegree.size() ? sb.toString() : ""; } }