Word Ladder

78 篇文章 0 订阅
24 篇文章 0 订阅

一开始自己以为是用dp来做,其实后来一想,这也不符合dp的3种常见类型。学习了答案才知,这是一道考的经典题目,用的是bfs。

下面这张图真的很形象,解释了里面两个for循环是做什么的,同时一定要记得匹配了一个word后,要从字典中删除,这样来避免重复查找和死循环。


/**
      * @param start, a string
      * @param end, a string
      * @param dict, a set of string
      * @return an integer
      */
    
    private class WordCount {
        public String word;
        public int count;
        public WordCount (String word, int count) {
            this.word = word;
            this.count = count;
        }
    }
    
    public int ladderLength(String start, String end, Set<String> dict) {
        // write your code here
        Queue<WordCount> queue = new LinkedList<>();
        dict.add(end);
        queue.offer(new WordCount(start, 1));
        
        while (!queue.isEmpty()) {
            WordCount wc = queue.poll();
            if (wc.word.equals(end)) {
                return wc.count;
            }
            String curS = wc.word;
            for (int i = 0; i < curS.length(); i++) {
                for (char c = 'a'; c <= 'z'; c++) {
                    char [] arrC = curS.toCharArray();
                    char temp = arrC[i];
                    arrC[i] = c;
                    String str = new String(arrC);
                    if (dict.contains(str)) {
                        queue.offer(new WordCount(str, wc.count + 1));
                        dict.remove(str);
                    }
                    arrC[i] = temp;
                }
            }
        }
        return 0;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值