LeetCode每日一题:单词梯 1

问题描述

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start ="hit"
end ="cog"
dict =["hot","dot","dog","lot","log"]
As one shortest transformation is"hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length5.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.

问题分析

其实一次变一个字母很适合构建图来做,构建好图之后只要求两点间的最小连通路径长度就行了(邻接表或者二维拓扑数组),但是这样构建图的时间复杂度是O(dict.length^2),直接超时
看了各位大佬的解答后,发现只要循环替换单词中字符从‘a-z’都试一遍,替换后的单词是否在dict中出现即可,复杂度降为O(26*word.length),直接降了一个维度了。

代码实现

 public int ladderLength(String start, String end, HashSet dict) {
        if (start.equals(end)) return 0;
        LinkedList queue = new LinkedList<>();
        HashMap dist = new HashMap<>();//保存变化的中间结果,变化一位之后的单词和从start变化过来的步数
        queue.offer(start);
        dist.put(start, 1);
        while (queue.isEmpty() == false) {
            String head = queue.poll();
            int headDist = dist.get(head);
            for (int i = 0; i < head.length(); i++) {
                for (char ch = 'a'; ch < 'z'; ch++) {
                    if (head.charAt(i) == ch) continue;
                    String newString = head;
                    StringBuilder stringBuilder = new StringBuilder(head);
                    stringBuilder.setCharAt(i, ch);
                    if (stringBuilder.toString().equals(end)) return headDist + 1;
                    if (dict.contains(stringBuilder.toString()) && dist.containsKey(stringBuilder.toString()) == false) {
                        queue.add(stringBuilder.toString());
                        dist.put(stringBuilder.toString(), headDist + 1);
                    }
                }
            }
        }
        return 0;
    }

你可能感兴趣的:(LeetCode每日一题:单词梯 1)