讨论/技术交流/面试题 17.22. 单词转换,求大神光临/
面试题 17.22. 单词转换,求大神光临

#求求给个说法啊
为什么它就运行不了呢?

public List<String> findLadders(String beginWord, String endWord, List<String> wordList) {
        Queue<String> queue = new LinkedList<>();   //用来走路的
        Map<String,String> visited = new HashMap(); //可以保存走过的word,还有它的父节点
        queue.add(beginWord);   //开始遍历
        Deque<String> list = new LinkedList<>();    //最后的返回值
        visited.put(beginWord,beginWord);
        while (!queue.isEmpty()){
            int size = queue.size();//这次的父类有几个
            for (int i = 0; i < size; i++){     //这波的父类遍历
                String s = queue.poll();
                if (s.equals(endWord)){     // successive match
                    list.addFirst(endWord);     //from end to begin
                    String t = endWord;
                    while (!t.equals(beginWord)){
                        t = visited.get(endWord);
                        list.addFirst(t);
                    }
                    return (List<String>) list;
                }
                for (var n : wordList){     //not match, add child node
                    if (isadj(s,n) && !visited.containsKey(n)){//is adj and not have visit
                        visited.put(n,s);
                        queue.add(n);
                    }
                }
            }
        }
        return (List<String>)list;
    }
    boolean isadj(String s, String n){
        int k = 0;
        for (int i = 0; i < s.length(); i++)
            if (s.charAt(i) != n.charAt(i))
                k++;
        return k == 1;
    }
1
共 0 个回复
暂无回复