Skip to content

Commit 54ca80d

Browse files
committed
Time: 91 ms (55.08%), Space: 47.1 MB (42.04%) - LeetHub
1 parent 443ad1a commit 54ca80d

File tree

1 file changed

+18
-15
lines changed

1 file changed

+18
-15
lines changed

0127-word-ladder/0127-word-ladder.java

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,29 @@
11
class Solution {
2-
public int ladderLength(String startWord, String targetWord, List<String> wordList) {
3-
4-
HashSet<String> st = new HashSet<>();
5-
for(String str :wordList){
6-
st.add(str);
2+
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
3+
HashSet<String> set = new HashSet<>();
4+
for(String word : wordList){
5+
set.add(word);
76
}
7+
88
Queue<Pair> que = new LinkedList<>();
9-
que.offer(new Pair(startWord,1));
10-
st.remove(startWord);
9+
que.offer(new Pair(beginWord,1));
10+
set.remove(beginWord);
11+
1112
while(!que.isEmpty()){
12-
String word =que.peek().word;
13-
int dist =que.peek().dist;
14-
que.poll();
15-
if(word.equals(targetWord) == true) return dist;
13+
Pair pp = que.poll();
14+
String curr = pp.word;
15+
int dist = pp.dist;
1616

17-
for(int i=0;i<word.length();i++){
17+
if(curr.equals(endWord)){
18+
return dist;
19+
}
20+
for(int i=0;i<curr.length();i++){
1821
for(char ch='a';ch<='z';ch++){
19-
char replace[] =word.toCharArray();
22+
char replace[] =curr.toCharArray();
2023
replace[i]=ch;
2124
String newreplaced =new String(replace);
22-
if(st.contains(newreplaced)==true){
23-
st.remove(newreplaced);
25+
if(set.contains(newreplaced)){
26+
set.remove(newreplaced);
2427
que.offer(new Pair(newreplaced,dist+1));
2528
}
2629
}

0 commit comments

Comments
 (0)