Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 字梯复杂性分析_Algorithm_Time Complexity - Fatal编程技术网

Algorithm 字梯复杂性分析

Algorithm 字梯复杂性分析,algorithm,time-complexity,Algorithm,Time Complexity,我想确保我正确地进行了时间复杂性分析。似乎有许多不同的分析 以防人们不知道问题,这是问题描述 给定两个单词(beginWord和endWord),以及词典的单词列表,找出从beginWord到endWord的最短转换序列的长度,如下所示: 一次只能更改一个字母。 每个转换的单词必须存在于单词列表中。请注意,beginWord不是经过转换的单词。 比如说, 鉴于: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lo

我想确保我正确地进行了时间复杂性分析。似乎有许多不同的分析

以防人们不知道问题,这是问题描述

给定两个单词(
beginWord
endWord
),以及词典的单词列表,找出从
beginWord
endWord
的最短转换序列的长度,如下所示:

一次只能更改一个字母。 每个转换的单词必须存在于单词列表中。请注意,beginWord不是经过转换的单词。 比如说,

鉴于:

beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
因为一个最短的转换是“击中”->“热”->“点”->“狗”->“齿轮”, 返回其长度5

这是一个简单的BFS算法

    static int ladderLength(String beginWord, String endWord, List<String> wordList) {
    int level = 1;
    Deque<String> queue = new LinkedList<>();
    queue.add(beginWord);
    queue.add(null);
    Set<String> visited = new HashSet<>();
    // worst case we can add all dictionary thus N (len(dict)) computation
    while (!queue.isEmpty()) {
        String word = queue.removeFirst();
        if (word != null) {
            if (word.equals(endWord)) {
                return level;
            }
            // m * 26 * log N
            for (int i = 0; i < word.length(); i++) {
                char[] chars = word.toCharArray();
                for (char c = 'a'; c <= 'z'; c++) {
                    chars[i] = c;
                    String newStr = new String(chars);
                    if (!visited.contains(newStr) && wordList.contains(newStr)) {
                        queue.add(newStr);
                        visited.add(newStr);
                    }
                }
            }
        } else {
            level++;
            if (!queue.isEmpty()) {
                queue.add(null);
            }
        }
    }
    return 0;
}
static int ladderLength(字符串开始字、字符串结束字、列表字列表){
智力水平=1;
Deque queue=new LinkedList();
queue.add(beginWord);
queue.add(null);
Set visted=新HashSet();
//最坏的情况下,我们可以添加所有字典,从而进行N(len(dict))计算
而(!queue.isEmpty()){
String word=queue.removeFirst();
if(word!=null){
如果(字等于(尾字)){
回报水平;
}
//m*26*logn
for(int i=0;i这是否正确?

列表
类型不会自动对其元素进行排序,而是“忠实地”按添加的顺序保存所有元素。因此
wordList.contains
实际上是
O(n)
。但是对于
哈希集
,例如
已访问的
,此操作是
O(1)
(摊销)所以请考虑切换到。

谢谢你的评论。你认为整体分析是正确的吗?