MCPcopy
hub / github.com/careercup/ctci / transform

Method transform

java/Chapter 18/Question18_10/Question.java:15–52  ·  view source on GitHub ↗
(String startWord, String stopWord, Set<String> dictionary)

Source from the content-addressed store, hash-verified

13public class Question {
14
15 public static LinkedList<String> transform(String startWord, String stopWord, Set<String> dictionary) {
16 startWord = startWord.toUpperCase();
17 stopWord = stopWord.toUpperCase();
18 Queue<String> actionQueue = new LinkedList<String>();
19 Set<String> visitedSet = new HashSet<String>();
20 Map<String, String> backtrackMap = new TreeMap<String, String>();
21
22 actionQueue.add(startWord);
23 visitedSet.add(startWord);
24
25 while (!actionQueue.isEmpty()) {
26 String w = actionQueue.poll();
27 // For each possible word v from w with one edit operation
28 for (String v : getOneEditWords(w)) {
29 if (v.equals(stopWord)) {
30 // Found our word! Now, back track.
31 LinkedList<String> list = new LinkedList<String>();
32 // Append v to list
33 list.add(v);
34 while (w != null) {
35 list.add(0, w);
36 w = backtrackMap.get(w);
37 }
38 return list;
39 }
40
41 // If v is a dictionary word
42 if (dictionary.contains(v)) {
43 if (!visitedSet.contains(v)) {
44 actionQueue.add(v);
45 visitedSet.add(v); // mark visited
46 backtrackMap.put(v, w);
47 }
48 }
49 }
50 }
51 return null;
52 }
53
54 private static Set<String> getOneEditWords(String word) {
55 Set<String> words = new TreeSet<String>();

Callers 1

mainMethod · 0.95

Calls 6

getOneEditWordsMethod · 0.95
putMethod · 0.80
addMethod · 0.45
isEmptyMethod · 0.45
getMethod · 0.45
containsMethod · 0.45

Tested by

no test coverage detected