Skip to content

Instantly share code, notes, and snippets.

@sopherwang
Created September 8, 2014 21:10
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 sopherwang/94917bb00a0c30267bab to your computer and use it in GitHub Desktop.
Save sopherwang/94917bb00a0c30267bab to your computer and use it in GitHub Desktop.
Word Ladder
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