Files
java/src/com/hong/www/A27.java
T
2026-10-13 11:44:32 +08:00

65 lines
2.1 KiB
Java

package com.hong.www;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class A27 {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
HashSet<String> history = new HashSet<>(wordList);
ArrayList<String> now = new ArrayList<>();
int times=0;
now.add(beginWord);
while (true) {
ArrayList<String> now1 = new ArrayList<>();
times++;
for (String nowword : now) {
char[] temp = nowword.toCharArray();
for (int i = 0; i < temp.length; i++) {
for (char j = 'a'; j <= 'z'; j++) {
char[] temp1 = Arrays.copyOf(temp, temp.length);
temp1[i] = j;
String u=new String(temp1);
if(history.contains(u)){
history.remove(u);
now1.add(u);
if(u.equals(endWord)){
return times+1;
}
}
/* for (String p : wordList) {
if (p.equals(u)&&!history.contains(p)) {
history.add(p);
now1.add(p);
if(p.equals(endWord)){
return times+1;
}
}
} */
}
}
}
if(now1.size()==0){
return 0;
}
now=now1;
}
//return 0;
}
public static void main(String[] args) {
A27 a27 = new A27();
List<String> list = new ArrayList<>();
list.add("hot");
list.add("dot");
list.add("dog");
list.add("lot");
list.add("log");
list.add("cog");
System.out.println(a27.ladderLength("hit", "cog", list));
}
}