【LeetCode】 127. Word Ladder 单词接龙(Medium)(JAVA)每日一题

【LeetCode】 127. Word Ladder 单词接龙(Medium)(JAVA)

题目地址: https://leetcode.com/problems/word-ladder/

题目描述:

Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

1. Only one letter can be changed at a time.
2. Each transformed word must exist in the word list.

Note:

* Return 0 if there is no such transformation sequence.
* All words have the same length.
* All words contain only lowercase alphabetic characters.
* You may assume no duplicates in the word list.
* You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output: 5

Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Output: 0

Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.

题目大意

给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:

1. 每次转换只能改变一个字母。
2. 转换过程中的中间单词必须是字典中的单词。

说明:

* 如果不存在这样的转换序列,返回 0。
* 所有单词具有相同的长度。
* 所有单词只由小写字母组成。
* 字典中不存在重复的单词。
* 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。

解题方法

  1. 这是一道考 BFS (广度优先搜索)的题目:一般找最近的路径、最小的数量都是 BFS 来做
  2. 采用广度优先搜索
    • 从 wordList 列表里找出和当前 string 只差一个字母的元素,放入列表里面,然后在 wordList 里面删除这个元素,避免重复搜索
    • 用一个 count 来表示当前层级的元素个数,每次到 0 说明这个层级已经遍历过一次了,结果就加一 : res ++
class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        List<String> list = new ArrayList<>();
        list.add(beginWord);
        int count = 1;
        int res = 1;
        while (list.size() > 0) {
            String cur = list.remove(0);
            count--;
            for (int i = 0; i < wordList.size(); i++) {
                if (check(cur, wordList.get(i))) {
                    if (endWord.equals(wordList.get(i))) return res + 1;
                    list.add(wordList.remove(i));
                    i--;
                }
            }
            if (count == 0) {
                res++;
                count = list.size();
            }
        }
        return 0;
    }

    public boolean check(String a, String b) {
        if (a.length() != b.length() || a.equals(b)) return false;
        int count = 0;
        for (int i = 0; i < a.length(); i++) {
            if (a.charAt(i) != b.charAt(i)) count++;
            if (count > 1) return false;
        }
        return count == 1;
    }
}

执行耗时:449 ms,击败了36.95% 的Java用户
内存消耗:38.7 MB,击败了96.41% 的Java用户

对判断只差一个字母的方法进行优化
  1. 因为题目里说了,只有 26 个小写字母,所以只要把 26 个小写字母遍历一遍就行
  2. 采用 set 的形式,这样判断的时候就不需要遍历了
class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        List<String> list = new ArrayList<>();
        Set<String> set = new HashSet<>();
        for (int i = 0; i < wordList.size(); i++) {
            set.add(wordList.get(i));
        }
        if (!set.contains(endWord)) return 0;
        list.add(beginWord);
        int count = 1;
        int res = 1;
        while (list.size() > 0) {
            String cur = list.remove(0);
            count--;
            char[] chars = cur.toCharArray();
            for (int i = 0; i < cur.length(); i++) {
                char curChar = chars[i];
                for (char j = 'a'; j <= 'z'; j++) {
                    if (chars[i] == j) continue;
                    chars[i] = j;
                    String temp = String.valueOf(chars);
                    if (endWord.equals(temp)) return res + 1;
                    if (set.contains(temp)) {
                        list.add(temp);
                        set.remove(temp);
                    }
                }
                chars[i] = curChar;
            }
            if (count == 0) {
                res++;
                count = list.size();
            }
        }
        return 0;
    }
}

执行耗时:77 ms,击败了64.52% 的Java用户
内存消耗:40.4 MB,击败了53.52% 的Java用户

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值