1. 程式人生 > >Google - Reconstruct To Chain

Google - Reconstruct To Chain

/*
4. 給你一串input,比如:
A -> B
B -> C
X -> Y
Z -> X
。
。
。
然後讓你設計一個data structure來存這些關係,最後讀完了以後呢要輸出這些關係鏈:[A -> B -> C, Z -> X -> Y]
如果遇到invalid的case就直接raise error,比如你已經有了A->B->C,這時候給你一個D->C或者B->D就是invalid的。
followup我感覺就是他看你什麼case沒有cover就提出來然後問你怎麼改你的程式碼和data structure
比如遇到A->B兩次,再比如遇到環
這題相當開放,面試官說他遇到過4,5種不同的解法,總之就是最好保證insert是O(1), reconstruct是O(n)

補充內容 (2018-11-19 01:02):
第四題好像說是關係鏈有點誤導大家,它題目的意思更像是directed graph,然後每次讀進來的都是一條edge,要求是你的graph裡只能有鏈條,不能有branch,不能有cycle,所以假設你有A->B->C,這時候又來了一個A->C算錯
*/ public class Main { public static void main(String[] args) { String[] strs = {"A -> B", "B -> C", "X -> Y", "Z -> X"}; try{ Solution s = new Solution(); s.insert(strs); s.reconstruct(); //System.out.println("Hello World!");
} catch(Exception e){ e.printStackTrace(); } } } class Solution{ class Node { char val; Node pre; Node next; public Node(char v){ val = v; } } HashMap<Character, Node> map= new
HashMap<>(); HashSet<Character> roots = new HashSet<>(); public void insertSingle(String str) throws Exception{ String[] strs = str.split(" -> "); char parent = strs[0].charAt(0); char child = strs[1].charAt(0); //check parent side Node pNode = null; if(!map.containsKey(parent)){ pNode = new Node(parent); map.put(parent, pNode); roots.add(parent); } else{ if(map.get(parent).next != null && map.get(parent).next.val != child){ throw new Exception("multiple children!"); } pNode = map.get(parent); } //check child side Node cNode = null; if(!map.containsKey(child)){ cNode = new Node(child); map.put(child, cNode); } else{ if(map.get(child).pre != null && map.get(child).pre.val != parent){ throw new Exception("multiple parents!"); } if(roots.contains(child)){ roots.remove(child); } cNode = map.get(child); } pNode.next = cNode; cNode.pre = pNode; } public void insert(String[] strs) throws Exception{ for(String str : strs){ insertSingle(str); } } //cycle will be detected here by adding an array to check if the node is visited or not. public void reconstruct() throws Exception{ for(char root : roots){ Node node = map.get(root); while(node != null){ System.out.print(node.val); node = node.next; } System.out.println(""); } } }