All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0101_0200.s0127_word_ladder.Solution Maven / Gradle / Ivy

There is a newer version: 1.24
Show newest version
package g0101_0200.s0127_word_ladder;

// #Hard #Top_Interview_Questions #String #Hash_Table #Breadth_First_Search
// #Graph_Theory_I_Day_12_Breadth_First_Search
// #2022_06_23_Time_37_ms_(94.58%)_Space_54.1_MB_(66.08%)

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Solution {
    public int ladderLength(String beginWord, String endWord, List wordDict) {
        Set beginSet = new HashSet<>();
        Set endSet = new HashSet<>();
        Set wordSet = new HashSet<>(wordDict);
        Set visited = new HashSet<>();
        if (!wordDict.contains(endWord)) {
            return 0;
        }
        int len = 1;
        int strLen = beginWord.length();
        beginSet.add(beginWord);
        endSet.add(endWord);
        while (!beginSet.isEmpty() && !endSet.isEmpty()) {
            if (beginSet.size() > endSet.size()) {
                Set temp = beginSet;
                beginSet = endSet;
                endSet = temp;
            }
            Set tempSet = new HashSet<>();
            for (String s : beginSet) {
                char[] chars = s.toCharArray();
                for (int i = 0; i < strLen; i++) {
                    char old = chars[i];
                    for (char j = 'a'; j <= 'z'; j++) {
                        chars[i] = j;
                        String temp = new String(chars);
                        if (endSet.contains(temp)) {
                            return len + 1;
                        }
                        if (!visited.contains(temp) && wordSet.contains(temp)) {
                            tempSet.add(temp);
                            visited.add(temp);
                        }
                    }
                    chars[i] = old;
                }
            }
            beginSet = tempSet;
            len++;
        }
        return 0;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy