Alien Dictionary
要自己从头建 Graph ,就应该直接从 Node 写起,记 state, children, indegree 都方便。
题意解析:
public class Solution {
private class Node{
int chrInt;
int state;
int indegree;
ArrayList<Integer> children;
public Node(int chrInt){
this.chrInt = chrInt;
state = 0;
indegree = 0;
children = new ArrayList<Integer>();
}
public char getChar(){
return (char) (this.chrInt + 'a');
}
}
public String alienOrder(String[] words) {
HashMap<Integer, Node> map = new HashMap<>();
StringBuilder sb = new StringBuilder();
if(words.length == 1) return words[0];
for(int i = 0; i < words.length - 1; i++){
learn(words[i], words[i + 1], map);
}
for(int i : map.keySet()){
if(map.get(i).state == 0 && dfs(i, sb, map)) return "";
}
return sb.reverse().toString();
}
private boolean dfs(int cur, StringBuilder sb, HashMap<Integer, Node> map) {
Node node = map.get(cur);
node.state = 1;
boolean hasCycle = false;
for(int i = 0; i < node.children.size(); i++){
int next = node.children.get(i);
if(map.get(next).state == 1) hasCycle = true;
else if (map.get(next).state == 0) {
hasCycle = hasCycle || dfs(next, sb, map);
}
}
node.state = 2;
sb.append(node.getChar());
return hasCycle;
}
private void learn(String word1, String word2, HashMap<Integer, Node> map){
int ptr1 = 0;
int ptr2 = 0;
while(ptr1 < word1.length() && ptr2 < word2.length()){
int parent = word1.charAt(ptr1++) - 'a';
int child = word2.charAt(ptr2++) - 'a';
if(!map.containsKey(parent)) map.put(parent, new Node(parent));
if(!map.containsKey(child)) map.put(child, new Node(child));
if(parent != child){
Node p = map.get(parent);
Node c = map.get(child);
if(!p.children.contains(child)){
p.children.add(child);
c.indegree ++;
}
break;
}
}
while(ptr1 < word1.length()){
int node = word1.charAt(ptr1++) - 'a';
if(!map.containsKey(node)) map.put(node, new Node(node));
}
while(ptr2 < word2.length()){
int node = word2.charAt(ptr2++) - 'a';
if(!map.containsKey(node)) map.put(node, new Node(node));
}
}
}同样的结构, BFS 写法:
不建 Node class 而用 HashMap 的做法如下:
自己在写这题白板的时候犯了一个小错误,就是一旦发现了 char1 != char2 ,处理完了要记得 break,不要乱学新的 edge 出来。
Last updated