27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Solutions</strong> to Chapter 20 | Hard<br />

20.8 Given a string s <strong>and</strong> an array of smaller strings T, design a method to search s for each<br />

small string in T.<br />

SOLUTION<br />

pg 91<br />

First, create a suffix tree for s. For example, if your word were bibs, you would create <strong>the</strong> following<br />

tree:<br />

B<br />

I<br />

S<br />

I<br />

S<br />

B<br />

B<br />

S<br />

S<br />

Then, all you need to do is search for each string in T in <strong>the</strong> suffix tree. Note that if “B” were a<br />

word, you would come up with two locations.<br />

1 public class SuffixTree {<br />

2 SuffixTreeNode root = new SuffixTreeNode();<br />

3 public SuffixTree(String s) {<br />

4 for (int i = 0; i < s.length(); i++) {<br />

5 String suffix = s.substring(i);<br />

6 root.insertString(suffix, i);<br />

7 }<br />

8 }<br />

9<br />

10 public ArrayList getIndexes(String s) {<br />

11 return root.getIndexes(s);<br />

12 }<br />

13 }<br />

14<br />

15 public class SuffixTreeNode {<br />

16 HashMap children = new<br />

17 HashMap();<br />

18 char value;<br />

19 ArrayList indexes = new ArrayList();<br />

CareerCup.com<br />

2 8 8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!