Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. public class Solution {
  2. public int ladderLength(String start, String end, HashSet<String> dict) {
  3.  
  4. if (dict.size() == 0)
  5. return 0;
  6.  
  7. LinkedList<String> wordQueue = new LinkedList<String>();
  8. LinkedList<Integer> distanceQueue = new LinkedList<Integer>();
  9.  
  10. wordQueue.add(start);
  11. distanceQueue.add(1);
  12.  
  13.  
  14. while(!wordQueue.isEmpty()){
  15. String currWord = wordQueue.pop();
  16. Integer currDistance = distanceQueue.pop();
  17.  
  18. if(currWord.equals(end)){
  19. return currDistance;
  20. }
  21.  
  22. for(int i=0; i<currWord.length(); i++){
  23. char[] currCharArr = currWord.toCharArray();
  24. for(char c='a'; c<='z'; c++){
  25. currCharArr[i] = c;
  26.  
  27. String newWord = new String(currCharArr);
  28. if(dict.contains(newWord)){
  29. wordQueue.add(newWord);
  30. distanceQueue.add(currDistance+1);
  31. dict.remove(newWord);
  32. }
  33. }
  34. }
  35. }
  36.  
  37. return 0;
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement