标签: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; } }
标签:find return play not system empty pre sys length
原文地址:http://www.cnblogs.com/yunyouhua/p/7052642.html