Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Created August 13, 2014 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jingz8804/fc20b969e1c6d7beaede to your computer and use it in GitHub Desktop.
Save jingz8804/fc20b969e1c6d7beaede to your computer and use it in GitHub Desktop.
#leetcode wordladder
import java.util.Queue;
import java.util.LinkedList;
import java.util.Hashtable;
import java.util.Arrays;
public class Solution {
public int ladderLength(String start, String end, Set<String> dict) {
if (start.equals(end))
return 1;
// add the string end to the dict
dict.add(end);
Queue<String> q = new LinkedList<String>();
q.offer(start);
Hashtable<String, Integer> lengths = new Hashtable<String, Integer>();
lengths.put(start, 1);
while (q.size() > 0) {
String current = q.poll();
if (current.equals(end))
break;
int tmpLen = lengths.get(current);
// discover the edges
// we need to change every single character in the current string
// for 26 times
// and to see if the new word is in the dict and not in the lengths
// table
for (int i = 0; i < current.length(); i++) {
char[] word = current.toCharArray();
char ch = word[i];
for (char c = 'a'; c <= 'z'; c++) {
word[i] = c;
String newWord = new String(word);
if (dict.contains(newWord) && !lengths.containsKey(newWord)) {
lengths.put(newWord, tmpLen + 1);
q.offer(newWord);
}
}
word[i] = ch; // remember to change it back before we move on to
// the next position
}
}
if (lengths.containsKey(end))
return lengths.get(end);
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment