6/19/2014

135. Word Ladder

public class Solution {
    public int ladderLength(String start, String end, HashSet<String> dict) {
        if (dict.size()==0) return 0;
       
        LinkedList<String> wordQueue = new LinkedList<String> ();
        LinkedList<Integer> stepQueue = new LinkedList<Integer> ();
       
        wordQueue.add(start);
        stepQueue.add(1);
       
        while (!wordQueue.isEmpty()) {
            String curWord = wordQueue.pop();
            Integer curStep = stepQueue.pop();
           
            if (curWord.equals(end)) return curStep;
           
            for (int i=0; i<curWord.length(); i++) {
                char[] curCharArr = curWord.toCharArray();
                for (char c='a'; c<='z'; c++) {
                    curCharArr[i] = c;
                    String newWord = new String(curCharArr);
                    if (dict.contains(newWord)) {
                        wordQueue.add(newWord);
                        stepQueue.add(curStep+1);
                        dict.remove(newWord);
                    }
                }
            }
        }
       
        return 0;
    }
}

没有评论:

发表评论