码迷,mamicode.com
首页 > 其他好文 > 详细

word ladder

时间:2017-06-20 09:39:14      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:find   return   play   not   system   empty   pre   sys   length   

超时

技术分享
public class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        //You may assume beginWord and endWord are non-empty and are not the same.
        if (wordList == null) {
            return 0;
        }
        int length = 2;
        
        Queue<String> queue = new LinkedList<>();
        Set<String> hash = new HashSet<>();
        
        queue.add(beginWord);
        hash.add(beginWord);
        
        boolean find = false;
        while (!queue.isEmpty()) {
            int size = queue.size();
            //System.out.println("length" + length);
            for (int k = 0; k < size; k++) {
                String node = queue.poll();
                //System.out.println("一层" + node);
                if (node.equals(endWord)) {
                    find = true;
                    return ++length;
                    
                }
                for (int i = 0; i < wordList.size(); i++) {
                    int count = 0;
                    String next = wordList.get(i);
                    
                    if (!hash.contains(next)) {
                    //System.out.print("next");
                    //System.out.println(next);
                        for (int j = 0; j < node.length(); j++) {
                            if (! (node.substring(j, j + 1).equals(next.substring(j, j + 1)))) {
                                count++;
                            }
                        } 
                        if (count == 1) {
                            if (next.equals(endWord)) {
                                return length;
                            }
                            queue.add(next);
                            hash.add(next);
                            //System.out.print("add");
                            //System.out.println(next);
                        }
                    }
                }
                
            }
            length++;
        }
        return 0;
    }
}
View Code

 

word ladder

标签:find   return   play   not   system   empty   pre   sys   length   

原文地址:http://www.cnblogs.com/yunyouhua/p/7052642.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!