2016-07-20 19 views
1
I have encountered an interview question 
    「Implement a phone directory using Data Structures」     

我希望它使用tries.By與試圖解決它來解決手機目錄,我試着用兩個嘗試,一個名字,另一個電話號碼, 但我面臨的一個困難。
想,我一定要添加三個條目(AB「112」 BC「124」 CD「225」 ) 那麼,如果我查詢號命名爲‘225’,我怎麼回CD。 也就是說,這兩個嘗試將如何鏈接。實現使用兩次嘗試

One approach I was thinking was taking two pointers in both the tries. 
    These pointers will point to the first and last word in the other trie. 
    For example,if the structures are as follows: 

    Struct nametrie        
    {              
    Struct nametrie *child[26]; 
    struct phonetrie*head,*tail; 
    struct phonetrie*root;  

    -----------  
    }              

     Struct phonetrie 
    { 
      struct phonetrie*child[9]; 
      struct nametrie*head,*tail; 
      struct nametrie*root; 
     ----------- 
     } 


    Then for AB 「112」, 
    Name trie willstore head(1) and tail (2). 

但我認爲這種做法不會重複項工作(一個名稱和多個號碼。)

Can someone please explain a good approach.I am not looking for code but good understanding of approach,may be via diagram or algorithm. 

回答

0

我不知道的C,所以我不能在你的代碼註釋。

使用嘗試的想法是有效的。

你似乎缺少節點可以嘗試

在樹上的節點有兩個主要組成部分

  1. 它具有數據可以是童裝的anytype類型
  2. 列表持什麼樣的數據(或左邊,右邊的兒童)或任何兒童組合

我們在這裏要做的是,我們將添加另一個字段到每個節點,並將其稱爲值「theValu E」

所以特里樹節點將這個樣子

Class TrieNode{ 
public char theChar; 
public String theValue; 
public List<TrieNode> children; 
} 

所以對於正向查找(名稱到手機)你構建一個特里和匹配的目錄條目的節點上,您將theValue設置爲entrie。

您需要創建第二個線索,爲反向查找(手機名)做同樣的

所以給你比如它是如何將看起來像這個數據將是

(AB「 112」 AC‘124’ACD「225」 )

//create nodes 
TrieNode root = new TrieNode(); 
TrieNode A = new TrieNode(); 
A.theChar = 'A'; 
TrieNode B = new TrieNode(); 
A.theChar = 'B'; 
TrieNode C = new TrieNode(); 
A.theChar = 'C'; 
TrieNode C2 = new TrieNode(); 
A.theChar = 'C'; 
TrieNode D = new TrieNode(); 
A.theChar = 'D'; 
//link nodes together 
root.children = new ArrayList<>(); 
root.children.add(A); 
A.children = new ArrayList<>(); 
A.children.add(B); 
A.children.add(C); 
B.children = new ArrayList<>(); 
B.children.add(C2); 
//fill the data 
B.theValue = "112"; 
C.theValue = "124"; 
C2.theValue = "225"; 

現在你可以輕鬆穿越這個特里,當你到達一個節點,whant檢查值只是讀theValue

我希望它是明確

+0

:對於反向查找,它不會工作,這是從數量到name.For這一點,你必須創建另一個trie.If你包括值字段在特里還,那麼相同的值被存儲在twice.Once線索從從根到葉節點和其他時間在值字段中第二線索 – KIMchi

+0

@KIMchi即完全正確的。所以你將有重疊,但你會得到在這兩種情況下 – Hani

+0

快速搜索訪問:可以把它也可以不重複進行上有什麼建議? – KIMchi

相關問題