25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Solutions to Chapter 20 | Hard<br />

20 public SuffixTreeNode() { }<br />

21<br />

22 public void insertString(String s, int index) {<br />

23 indexes.add(index);<br />

24 if (s != null && s.length() > 0) {<br />

25 value = s.charAt(0);<br />

26 SuffixTreeNode child = null;<br />

27 if (children.containsKey(value)) {<br />

28 child = children.get(value);<br />

29 } else {<br />

30 child = new SuffixTreeNode();<br />

31 children.put(value, child);<br />

32 }<br />

33 String remainder = s.substring(1);<br />

34 child.insertString(remainder, index);<br />

35 }<br />

36 }<br />

37<br />

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

39 if (s == null || s.length() == 0) {<br />

40 return indexes;<br />

41 } else {<br />

42 char first = s.charAt(0);<br />

43 if (children.containsKey(first)) {<br />

44 String remainder = s.substring(1);<br />

45 return children.get(first).getIndexes(remainder);<br />

46 }<br />

47 }<br />

48 return null;<br />

49 }<br />

50 }<br />

51<br />

52 public class Question {<br />

53 public static void main(String[] args) {<br />

54 String testString = “mississippi”;<br />

55 String[] stringList = {“is”, “sip”, “hi”, “sis”};<br />

56 SuffixTree tree = new SuffixTree(testString);<br />

57 for (String s : stringList) {<br />

58 ArrayList list = tree.getIndexes(s);<br />

59 if (list != null) {<br />

60 System.out.println(s + “: “ + list.toString());<br />

61 }<br />

62 }<br />

63 }<br />

64 }<br />

2 8 9<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Additional Review Problems

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

Saved successfully!

Ooh no, something went wrong!