Super Easy Java Solution


  • 0
    R
    public int ladderLength(String begin, String endWord, Set<String> wordList) {
            Queue<String> queue = new LinkedList<String>();
    		wordList.add(endWord);
    		queue.add(begin);
    		int dist = 1;
    		while (!queue.isEmpty()) {
    		  for (int size = queue.size(); size > 0; size--) {
    			String word = queue.remove();
    			if (endWord.equals(word)) {
    				return dist;
    			}
    			char arr[] = word.toCharArray();
    			for (int i = 0; i < arr.length; i++) {
    				char ch = arr[i];
    				for (char j = 'a'; j <= 'z'; j++) {
    					arr[i] = j;
    					word = String.valueOf(arr);
    					if (wordList.contains(word)) {
    						queue.add(word);
    						wordList.remove(word);
    					}
    					arr[i] = ch;
    				}
    			}
    		  }
    		  dist++;
    		}
    		return 0;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.