Advertisement
1988coder

127. Word Ladder

Dec 8th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.31 KB | None | 0 0
  1. /*
  2. Time Complexity: O(N * L)
  3. Space Complexity: O(N * L)
  4.  
  5. N = Number of words in the wordList
  6. L = Average length of the words in the wordList.
  7.  
  8. Questions to be asked to Interviewer:
  9. 1. If word ladder is "hot" -> "hit" .. is the result 1 or 2.
  10. 2. Is end word always part of wordList.
  11. */
  12. class Solution {
  13.     public int ladderLength(String beginWord, String endWord, List<String> wordList) {
  14.         HashSet<String> beginSet = new HashSet<String>();
  15.         HashSet<String> endSet = new HashSet<String>();
  16.         HashSet<String> visitedSet = new HashSet<String>();
  17.         HashSet<String> wordListSet = new HashSet<String>();
  18.        
  19.         for (String word : wordList) {
  20.             wordListSet.add(word);
  21.         }
  22.        
  23.         beginSet.add(beginWord);
  24.        
  25.         if (wordListSet.contains(endWord)) {
  26.             endSet.add(endWord);
  27.         } else {
  28.             return 0;
  29.         }
  30.        
  31.         int ladderLength = 1;
  32.         int wordLength = beginWord.length();
  33.        
  34.         while (!beginSet.isEmpty()) {
  35.             if (beginSet.size() > endSet.size()) {
  36.                 HashSet<String> swapSet = beginSet;
  37.                 beginSet = endSet;
  38.                 endSet = swapSet;
  39.             }
  40.            
  41.             HashSet<String> tempSet = new HashSet<String>();
  42.            
  43.             for (String word : beginSet) {
  44.                 char[] wordCharArray = word.toCharArray();
  45.                 for (int i = 0; i < wordLength; i++) {
  46.                     char old = wordCharArray[i];
  47.                     for (char c = 'a'; c <= 'z'; c++) {
  48.                         wordCharArray[i] = c;
  49.                         String target = new String(wordCharArray);
  50.                        
  51.                         if (endSet.contains(target)) {
  52.                             return ladderLength + 1;
  53.                         }
  54.                        
  55.                         if (!visitedSet.contains(target) && wordListSet.contains(target)) {
  56.                             visitedSet.add(target);
  57.                             tempSet.add(target);
  58.                         }
  59.                     }
  60.                     wordCharArray[i] = old;
  61.                 }
  62.             }
  63.            
  64.             beginSet = tempSet;
  65.             ladderLength++;
  66.         }
  67.        
  68.         return 0;
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement