0
点赞
收藏
分享

微信扫一扫

WebSocketServer+redis实时更新页面数据

爱喝酒的幸福人 2024-02-11 阅读 10

文章目录

思路

解题方法

复杂度

时间复杂度:

空间复杂度:

Code

class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        // 总词汇表
        Set<String> dict = new HashSet<>(wordList);
        if (!dict.contains(endWord)) {
            return 0;
        }
        // 数据量小的一侧
        Set<String> smallLevel = new HashSet<>();
        // 数据量大的一侧
        Set<String> bigLevel = new HashSet<>();
        // 数据量小的下一侧
        Set<String> nextLevel = new HashSet<>();
        smallLevel.add(beginWord);
        bigLevel.add(endWord);
        for (int len = 2; !smallLevel.isEmpty(); len++) {
            for (String w : smallLevel) {
                // 从小的一侧拓展
                char[] word = w.toCharArray();
                for (int j = 0; j < word.length; j++) {
                    char old = word[j];
                    for (char change = 'a'; change <= 'z'; change++) {
                        if (change != old) {
                            word[j] = change;
                            String next = String.valueOf(word);
                            if (bigLevel.contains(next)) {
                                return len;
                            }
                            if (dict.contains(next)) {
                                dict.remove(next);
                                nextLevel.add(next);
                            }
                        }
                    }
                    word[j] = old;
                }

            }
            if (nextLevel.size() <= bigLevel.size()) {
                // 交换当前层和较小层
                Set<String> temp = smallLevel;
                smallLevel = nextLevel;
                nextLevel = temp;
            } else {
                // 当前层大于较大层 交换当前层和较大层 较大层和较小层
                Set<String> temp = smallLevel;
                smallLevel = bigLevel;
                bigLevel = nextLevel;
                nextLevel = temp;
            }
            nextLevel.clear();
        }
        return 0;
    }
}
举报

相关推荐

0 条评论