首页 > 代码库 > word ladder
word ladder
超时
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; } }
word ladder
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。