部分文章内容为公开资料查询整理,原文出处可能未标注,如有侵权,请联系我,谢谢。邮箱地址:gnivor@163.com ►►►需要气球么?请点击我吧!

*LeetCode--126.Word Ladder II 127. Word Ladder

Word Ladder 解析:http://blog.csdn.net/yutianzuijin/article/details/12887747

利用BFS

public static int ladderLength(String start, String end, Set<String> dict) {
    if (start == null||end==null||start.equals(end)||start.length()!= end.length())
        return 0;
    if (isOneWordDiff(start, end))
        return 2;

    Queue<String> queue = new LinkedList<String>();
    HashMap<String, Integer> dist = new HashMap<String, Integer>(); //存放单词在第几层

    queue.add(start);
    dist.put(start, 1);

    while (!queue.isEmpty()) {
        String head = queue.poll();
        int headDist = dist.get(head);
        // 从每一个位置开始替换成a~z
        for (int i = 0; i < head.length(); i++) {
            for (char j = 'a'; j < 'z'; j++) {
                if (head.charAt(i) == j) continue;

                StringBuilder sb = new StringBuilder(head);
                sb.setCharAt(i, j);
                if (sb.toString().equals(end))
                    return headDist + 1;
                if (dict.contains(sb.toString())&&!dist.containsKey(sb.toString())) {
                    queue.add(sb.toString());
                    dist.put(sb.toString(), headDist + 1);
                }
            }
        }
    }
    return 0;
}

private static boolean isOneWordDiff(String a, String b) {
    int diff = 0;
    for (int i = 0; i < a.length(); i++) {
        if (a.charAt(i) != b.charAt(i)) {
            diff++;
            if (diff >= 2)
                return false;
        }
    }
    return diff == 1;
}

 

Word Ladder II 解析:http://blog.csdn.net/worldwindjp/article/details/19301355

public class Solution2 {
    public static void main(String[] args) {
        String beginWord = "hat" ;
        String endWord = "cog";
        Set<String> set = new HashSet<String>();
        set.add("hot");
        set.add("dot");
        set.add("dog");
        set.add("lot");
        set.add("log");
        set.add("hac");
        Solution2 s = new Solution2();
        List<List<String>> solu = s.findLadders(beginWord,endWord,set);
        System.out.println(solu);
    }    

    //记录每个单词所在的层数  
    HashMap<String,Integer> path = new HashMap<String,Integer>();  
    //bfs生成path  
    public void bfs(String start, String end, Set<String> dict) {  
        Queue<String> queue = new LinkedList<String>();  
        queue.add(start);  
        path.put(start,0);  
        String current;  
        while(!queue.isEmpty()) {  
            current = (String)queue.poll();  
            if(current==end) {  
                continue;  
            }  
            for(int i=0;i<current.length();i++) {  
                char[] strCharArr = current.toCharArray();  
                for(char ch='a';ch<='z';ch++) {  
                    if(strCharArr[i]==ch) {  
                        continue;  
                    }  
                    strCharArr[i] = ch;  
                    String newWord = new String(strCharArr);  
                    if(newWord.equals(end)==true||dict.contains(newWord)) {  
                        //每个单词在path中只能出现一次,也就是每个单词只能出现在一层中,
                        //这样就很巧妙的解决了环的问题。  
                        if(path.get(newWord)==null) {  
                            int depth = (int)path.get(current);  
                            path.put(newWord,depth + 1);  
                            queue.add(newWord);  
                        }  
                    }  
                }  
            }  
        }  
    }  
    //从目标单词往回找开始单词,记录所有路径  
    public void dfs(String end, String start, Set<String> dict, 
            List<String> pathArray,List<List<String>> result) {  
        //找到了,需要reverse加入的所有单词  
        if(end.equals(start)==true) {  
            pathArray.add(start);  
            Collections.reverse(pathArray);  
            result.add(pathArray);  
            return;  
        }  
        if(path.get(end)==null) {  
            return;  
        }  
        pathArray.add(end);  
        int nextDepth = (int)path.get(end) - 1;  
        for(int i=0;i<end.length();i++) {  
            char[] strCharArr = end.toCharArray();  
            for(char ch='a';ch<='z';ch++) {  
                if(strCharArr[i]==ch) {  
                    continue;  
                }  
                strCharArr[i] = ch;  
                String newWord = new String(strCharArr);  
                //只相差一个字母同时这个单词所在的层数也是当前单词的上一层  
                if(path.get(newWord)!=null&&(path.get(newWord)==nextDepth)) {  
                    ArrayList<String> newPathArray = new ArrayList<String>(pathArray);  
                    dfs(newWord,start,dict,newPathArray,result);  
                }  
            }  
        }  
    }  

    public List<List<String>> findLadders(String beginWord, String endWord, Set<String> wordList) {  
        List<List<String>> result = new ArrayList<List<String>>();  
        List<String> path = new ArrayList<String>();  
        if(beginWord==null||endWord==null||beginWord.length()!=endWord.length()) {  
            return result;  
        }  
        bfs(beginWord, endWord, wordList);  
        System.out.println(this.path);
        dfs(endWord,beginWord, wordList, path, result);  
        return result;  
    }  
}

 

posted @ 2015-09-25 22:03  流了个火  阅读(153)  评论(0)    收藏  举报
►►►需要气球么?请点击我吧!►►►
View My Stats