LeetCode – Word Ladder

题目描述

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 and each intermediate word must exist in the dictionary. For example, given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
One shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", the program should return its length 5.

java实现

使用bfs进行实现

public class WordLadder {

    public static int shortestTransformationLength(Set<String> dict,String start,String end) {
        dict.add(end);
        LinkedList<WordNode> queue = new LinkedList<WordNode>();
        queue.add(new WordNode(start,1));

        while (!queue.isEmpty()) {
            WordNode wordNode = queue.poll();
            if (wordNode.word.equals(end)) {
                return wordNode.length;
            }

            String temp = wordNode.word;
            char[] chars = temp.toCharArray();

            for (int j = 0; j < chars.length;j ++) {
                for (char i = 'a'; i < 'z';i ++) {
                    if (chars[j] != i) {
                        char c = chars[j];
                        chars[j] = i;
                        String tempStr = new String(chars);
                        if (dict.contains(tempStr)) {
                            queue.add(new WordNode(tempStr,wordNode.length + 1));
                            dict.remove(tempStr);
                        }
                        chars[j] = c;
                    }
                }
            }

        }
        return -1;
    }

    public static class WordNode {
        public String word;
        public int length;

        public WordNode(String word,int length) {
            this.word = word;
            this.length = length;
        }
    }

    public static void main(String[] args) {
        String start = "hit";
        String end = "cog";
        String[] strs =  {"hot","dot","dog","lot","log"};
        Set<String> dict = new HashSet<String>();
        dict.addAll(Arrays.asList(strs));
        System.out.println(shortestTransformationLength(dict,start,end));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值