Created
September 8, 2014 21:10
-
-
Save sopherwang/94917bb00a0c30267bab to your computer and use it in GitHub Desktop.
Word Ladder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int ladderLength(String start, String end, Set<String> dict) | |
{ | |
if (start.length() != end.length()) | |
{ | |
return 0; | |
} | |
if (dict == null || dict.size() == 0) | |
{ | |
return 0; | |
} | |
Queue<String> wordQueue = new LinkedList<String>(); | |
Queue<Integer> distanceQueue = new LinkedList<Integer>(); | |
wordQueue.add(start); | |
distanceQueue.add(1); | |
while (!wordQueue.isEmpty()) | |
{ | |
String curWord = wordQueue.poll(); | |
Integer curDistance = distanceQueue.poll(); | |
if (curWord.equals(end)) | |
{ | |
return curDistance; | |
} | |
for (int i = 0; i < curWord.length(); i++) | |
{ | |
char[] chars = curWord.toCharArray(); | |
//watch out! here is char for a to z!!! | |
for (char c = 'a'; c <= 'z'; c++) | |
{ | |
chars[i] = c; | |
String newWord = new String(chars); | |
if (dict.contains(newWord)) | |
{ | |
wordQueue.add(newWord); | |
distanceQueue.add(curDistance + 1); | |
dict.remove(newWord); | |
} | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment