标签:dde while ict turn csdn for ash .net dict
Set会快很多
替换各个位置的字符 在wordDict里面判断存不存在
类似BFS
https://blog.csdn.net/u014532901/article/details/78820124
1 class Solution { 2 public int ladderLength(String beginWord, String endWord, List<String> wordList) { 3 if(!wordList.contains(endWord)) return 0; 4 Set<String> wordSet=new HashSet<>(wordList); 5 Queue<String> visited = new LinkedList<>(); 6 visited.offer(beginWord); 7 wordList.remove(beginWord); 8 int distance = 1; 9 int size = visited.size(); 10 while(!visited.isEmpty()) { 11 for(int j = 0 ; j < size; j++) { 12 String str = visited.poll(); 13 for(int k = 0; k < str.length(); k++) { 14 char[] arr = str.toCharArray(); 15 for(int i = 0; i < 26; i++) { 16 arr[k] = (char)(‘a‘ + i); 17 String str1 = new String(arr); 18 if(wordSet.contains(str1)) { 19 visited.offer(str1); 20 wordSet.remove(str1); 21 } 22 } 23 } 24 } 25 distance++; 26 size = visited.size(); 27 if(visited.contains(endWord)) { 28 break; 29 }else if(visited.isEmpty()) { 30 return 0; 31 } 32 } 33 return distance; 34 35 } 36 }
标签:dde while ict turn csdn for ash .net dict
原文地址:https://www.cnblogs.com/goPanama/p/9692183.html