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 10 Given two words of equal length that are in a dictionary, write a method to transform<br />

one word into ano<strong>the</strong>r word by changing only one letter at a time The new word you<br />

get in each step must be in <strong>the</strong> dictionary<br />

2 9 1<br />

EXAMPLE:<br />

SOLUTION<br />

Input: DAMP, LIKE<br />

Output: DAMP -> LAMP -> LIMP -> LIME -> LIKE<br />

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

pg 91<br />

Though this problem seems tough, it’s actually a straightforward modification of breadthfirst-search<br />

Each word in our “graph” branches to all words in <strong>the</strong> dictionary that are one edit<br />

away The interesting part is how to implement this—should we build a graph as we go? We<br />

could, but <strong>the</strong>re’s an easier way We can instead use a “backtrack map ” In this backtrack map,<br />

if B[v] = w, <strong>the</strong>n you know that you edited v to get w When we reach our end word, we can<br />

use this backtrack map repeatedly to reverse our path See <strong>the</strong> code below:<br />

1 LinkedList transform(String startWord, String stopWord,<br />

2 Set dictionary) {<br />

3 startWord = startWord.toUpperCase();<br />

4 stopWord = stopWord.toUpperCase();<br />

5 Queue actionQueue = new LinkedList();<br />

6 Set visitedSet = new HashSet();<br />

7 Map backtrackMap = new TreeMap();<br />

8<br />

9 actionQueue.add(startWord);<br />

10 visitedSet.add(startWord);<br />

11<br />

12 while (!actionQueue.isEmpty()) {<br />

13 String w = actionQueue.poll();<br />

14 // For each possible word v from w with one edit operation<br />

15 for (String v : getOneEditWords(w)) {<br />

16 if (v.equals(stopWord)) {<br />

17 // Found our word! Now, back track.<br />

18 LinkedList list = new LinkedList();<br />

19 // Append v to list<br />

20 list.add(v);<br />

21 while (w != null) {<br />

22 list.add(0, w);<br />

23 w = backtrackMap.get(w);<br />

24 }<br />

25 return list;<br />

26 }<br />

27 // If v is a dictionary word

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

Saved successfully!

Ooh no, something went wrong!