Java solution


  • 0
    S

    class WordNode{
    String word;
    int numSteps;

    public WordNode(String word, int numSteps){
        this.word = word;
        this.numSteps = numSteps;
    }
    

    }

    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
       LinkedList<WordNode> queue = new LinkedList<WordNode>();
        queue.add(new WordNode(beginWord, 1));
        while(!queue.isEmpty()) {
            WordNode top = queue.remove();
            String word = top.word;
            if(word.equals(endWord)){
                return top.numSteps;
            }
            int i=0;
            String newWord;
            while(i<wordList.size()) {
                newWord =wordList.get(i);
                if(diffCount(word, newWord) == 1) {
                    queue.add(new WordNode(newWord, top.numSteps+1));
                    wordList.remove(newWord);
                } else {
                    i++;
                }
            }
        }
        
        return 0;
    }
    
    public static int diffCount(String first, String second){
        int diff=0;
        for(int i=0;i<first.length();i++) {
            if(first.charAt(i)!=second.charAt(i)) {
                diff++;
            }
        }
        
        return diff;
    }

  • 0
    S

    There is no need to count all the differences. As soon as you reached 2 you know that words are not adjacent.


Log in to reply
 

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