LeetCode题解:Word Ladder

这篇博客探讨了如何找到从beginWord到endWord的最短变换序列,其中每次变换仅允许改变一个字母,且每个中间单词必须在字典中。例如,从'hit'到'cog'的最短变换是'hit'->'hot'->'dot'->'dog'->'cog',长度为5。博客还提到了当没有这样的变换序列时返回0,所有单词具有相同长度且仅包含小写字母。解决方案包括检查单词是否可以通过修改一个字母并查找字典来变换。
摘要由CSDN通过智能技术生成

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:

Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,

Given:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”]
As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
return its length 5.

Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.

题意:给定两个单词和字典,判断单词A是否能通过变换字典中的的单词,并不断向下变换为单词B

解决思路:修改单词中某个单词,然后看字典里是否存在该单词,存在则提取

代码:

public class Solution {
    public int ladderLength(String start, String end, Set<String> dict) {
        LinkedList<String> queue = new LinkedList<String>();
        queue.add(start);
        dict.add(end);
        int step = 0;

        while (!queue.isEmpty()) {
            LinkedList<String> level = new LinkedList<String>();
            step++;
            while (!queue.isEmpty()) {
                String q = queue.poll();
                if(q.equals(end))
                    return step;

                char[] t = q.toCharArray();
                for(int i = 0; i < start.length(); i++){
                    for(char c = 'a'; c <= 'z'; c++){
                        char temp = t[i];
                        t[i] = c;
                        String s = String.copyValueOf(t);
                        t[i] = temp;
                        if(dict.contains(s)){
                            level.add(s);
                            dict.remove(s);
                        }
                    }
                }
            }
            queue = level;
        }

        return 0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值