标签:rgs static hid 容量 alt 路径 int its src
public int ladderLength(String beginWord, String endWord, List<String> wordList) { HashSet<String> dict=new HashSet<String>(); if(wordList.size()==0 || wordList==null){ return 0; } for(String s:wordList){ dict.add(s); } HashSet<String> visited=new HashSet<String>(); Queue<String> queue=new LinkedList<String>(); if(beginWord.equals(endWord)){ return 1; } int pathLength=1; queue.add(beginWord); visited.add(beginWord); while(!queue.isEmpty()){ int size=queue.size(); pathLength++; for(int i=0;i<size;i++){ String word=queue.poll(); for(String nextWord:getNextWord(word,dict)){ if(!visited.contains(nextWord)){ if(nextWord.equals(endWord)){ return pathLength; } visited.add(nextWord); queue.add(nextWord); } } } } return 0; } private List<String> getNextWord(String word,HashSet<String> dict){ List<String> ret=new ArrayList<String>(); for(char c=‘a‘;c<=‘z‘;c++){ for(int i=0;i<word.length();i++){ if(c==word.charAt(i)){ continue; } String nextWord=wordReplace(word,i,c); if(dict.contains(nextWord)){ ret.add(nextWord); } } } return ret; } private String wordReplace(String word,int index,char c){ char[] newWord=word.toCharArray(); newWord[index]=c; return new String(newWord); }
二刷:
之前的单向BFS已经超时了,于是参考了双向BFS解法
双向BFS,复杂度更低,思想就是两个SET, 交替扩展,直到两个set有元素重合,即有一条可通路
/** * 双向BFS,复杂度更低,思想就是两个SET, 交替扩展,直到两个set有元素重合,即有一条可通路 */ public class WordLadder { public int ladderLength(String beginWord, String endWord, List<String> wordList) { int step = 0; Set<String> s1 = new HashSet<>(); Set<String> s2 = new HashSet<>(); Set<String> dict = new HashSet<>(); if (!wordList.contains(endWord)) return step; for (String word : wordList) dict.add(word); s1.add(beginWord); s2.add(endWord); while (!s1.isEmpty() && !s2.isEmpty()) { step++; if (s1.size() > s2.size()) swap(s1, s2); //每次都扩展容量小的那个set Set<String> tmpSet = new HashSet<>(); for (String word : s1) { for (String newWord : getNextWord(word)) { if (s2.contains(newWord)) return step + 1; if (!dict.contains(newWord)) continue; dict.remove(newWord); tmpSet.add(newWord); } } s1 = tmpSet; } return 0; } private List<String> getNextWord(String word) { List<String> res = new ArrayList<>(); res.add(word); for (int i = 0; i < word.length(); i++) { for (char c = ‘a‘; c <= ‘z‘; c++) { String newWord = replaceWord(word, i, c); res.add(newWord); } } return res; } private void swap(Object o1, Object o2) { Object tmp = o1; o1 = o2; o2 = tmp; } private String replaceWord(String word, int index, char c) { char[] newWord = word.toCharArray(); newWord[index] = c; return new String(newWord); } public static void main(String[] args) { WordLadder wordLadder = new WordLadder(); String[] strings = {"hot","dog"}; System.out.println(wordLadder.ladderLength("hot", "dog", Arrays.asList(strings))); } }
标签:rgs static hid 容量 alt 路径 int its src
原文地址:https://www.cnblogs.com/shawshawwan/p/9221096.html