ๅ ็บๆ็ไฝๆณๅจๆๅฐๆๆๆๅฐ wordset ๅ remove newword, ๆไปฅไธ้่ฆๅคไธๅ visited set ไพๆชขๆฅ
newest version
T:O(26*M^2), M: word_len ,N wordList_size, M^2 because newString also needs Mconstructing a new string (String.valueOf(cAry)) inside the loop is O(M) because it involves creating a new character array and copying M characters into itS:O(N), set size
classSolution {publicintladderLength(String beginWord,String endWord,List<String> wordList) {Set<String> set =newHashSet<>(wordList);if (!set.contains(endWord)) { // there is a edge casereturn0; }Queue<String> queue =newLinkedList<>();queue.offer(beginWord);int steps =1; // beginWord is already 1while (!queue.isEmpty()) {int size =queue.size();for (int q =0; q < size; q++) {String cur =queue.poll();if (endWord.equals(cur)) {return steps; }for (int i =0; i <cur.length(); i++) {for (char ch ='a'; ch <='z'; ch++) {char cha[] =cur.toCharArray(); cha[i] = ch;String newStr =newString(cha);if (set.contains(newStr)) {queue.offer(newStr);set.remove(newStr); //remember to remove } } } } steps++; }return0; // cant find endWord from beginWord's transform }}/*do BFShit for each char to replace with 26 chars if hit wordList put to queuetermial case is equal endWord*/
key is here
for (int i =0; i <cur.length(); i++) {for (char ch ='a'; ch <='z'; ch++) {char cha[] =cur.toCharArray();
and if we don't remove word from set, it will case inf loop,
when doing changes, ok, we geneare dog,
and add to queue, after this it generate hot...
hot generate dog again, and there is still dog in Set -> inf loop!!