LeetCode 127. 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:
    Only one letter can be changed at a time.
    Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
  • 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:
    这里写图片描述

  • 地址

问题分析

  • LeetCode 279. Perfect Squares 类似,同样是对问题进行抽象建模成一个图,利用BFS找无向图图中的最短路径问题
  • 注意,对于一个元素是否遍历过,可以用 visited[]数组或者 HashSet。
  • 如何知道当前层数,279中用的是包装成一个类,而该题的实现中是利用层序遍历中的那种方法。具体见实现。

代码实现

class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        //用set存储
        HashSet<String> set = new HashSet<>(wordList);
        LinkedList<String> queue = new LinkedList<>();
        //初始化
        queue.add(beginWord);
        int level = 1;//用来表示第几层
        while (! queue.isEmpty()) {
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                String popStr = queue.pop();
                if (popStr.equals(endWord)) {
                    //变化到 endWord,直接返回层数
                    return level;
                }
                char[] chs = popStr.toCharArray();
                //分别改变当前串的每一个字母,然后查set中是否有变化后的字符串,作为当前字符串的下一个
                for (int j = 0; j < chs.length; j++) {
                    for (int k = 0; k < 26; k++) {
                        char ch = (char)('a' + k);
                        if (ch == chs[j]) {//相同不考虑
                            continue;
                        }
                        char temp = chs[j];
                        chs[j] = ch;
                        String str = new String(chs);
                        if (set.contains(str)) {
                            queue.add(str);
                            //注意,如果不想改变原输入,只能用另外一个set存储已经遍历过的字符串
                            set.remove(str);
                        }
                        //还原
                        chs[j] = temp;
                    }
                }
            }
            //处理完该层,层数也要变化。
            ++level;
        }
        return 0;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值