25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Solutions to Chapter 20 | Hard<br />

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

small string in T<br />

SOLUTION<br />

CareerCup com<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 />

S<br />

B<br />

I<br />

B<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 />

I<br />

S B<br />

S<br />

S<br />

2 8 8

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

Saved successfully!

Ooh no, something went wrong!