Word Ladder (单词接龙)

http://www.lintcode.com/en/problem/word-ladder/

package com.LintCode.WordLadder;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class Solution {
    /*
     * @param start: a string
     * @param end: a string
     * @param dict: a set of string
     * @return: An integer
     */
    public int ladderLength(String start, String end, Set dict) {
        // write your code here
//        其实就是树的BFS遍历
        if (start.equals(end)) {
            return 1;
        }
        int step = 0;
//        当前数的深度
        List list = new ArrayList<>();
        list.add(start);
        int index = 0;
        dict.add(end);
        while (index < list.size()) {
            step++;
//            因为start没有加到list里边,所以先加1
            int count = list.size();
            while (index < count) {
//                每次遍历当前深度的所有节点
                String s = list.get(index);
                for (String temp : getNextWords(s, dict)) {
//                    找到它在字典时的下一个单词。
                    if (temp.equals(end)) {
//                        因为要添加的是下一层,所以要加1
                        return step + 1;
                    }
                    list.add(temp);
                }
                index++;
            }
        }
        System.out.println(list);
        return 0;
    }

    private ArrayList getNextWords(String word, Set dict) {
        ArrayList nextWords = new ArrayList();
        for (char c = 'a'; c <= 'z'; c++) {
            for (int i = 0; i < word.length(); i++) {
                if (c == word.charAt(i)) {
                    continue;
                }
                String nextWord = replace(word, i, c);
                if (dict.contains(nextWord)) {
                    nextWords.add(nextWord);
                    dict.remove(nextWord);
                }
            }
        }
        return nextWords;
    }

    private String replace(String s, int index, char c) {
        char[] chars = s.toCharArray();
        chars[index] = c;
        return new String(chars);
    }
}

你可能感兴趣的:(Word Ladder (单词接龙))