LeetCode(单词接龙-构造单词的通用状态)

20200415

题目 :单词接龙

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

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

说明

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

示例

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

输出: 5

解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
     返回它的长度 5。

Word_Ladder_2.png

上图的预处理帮我们构造了一个单词变换的通用状态。例如:Dog ----> D*g <---- DigDogDig 都指向了一个通用状态 D*g

code

class Solution{
    public int ladderLength(String beginWord, String endWord,List<String> wordList){
        int L = beginWord.length();
        Map<String, List<String>> allComboDict = new HashMap<>();
        wordList.forEach(
        	word -> {
                for(int i=0;i<L;i++){
                    String newWord = word.substring(0,i) + '*' + word.substring(i+1,L);
                    List<String> transformations = allComboDict.getOrDefault(newword,new ArrayList<>());
                    transformations.add(word);
                    allComboDict.put(newWord,transformations);
                }
            });
        Queue<Pair<String,Integer>> Q = new LinkedList<>();
        Q.add(new Pair(beginWord,1));
        
        Map<String, Boolean> visited = new HashMap<>();
        visited.put(beginWord,true);
        
        while(!Q.isEmpty()){
            Pair<String,Integer> node = Q.remove();
            String word = node.getKey();
            int level = node.getValue();
            for(int i=0;i<L;i++){
                String newWord = word.substring(0,i)+'*'+word.substring(i+1,L);
                
                for(String adjacentWord : allComboDict.getOrDefault(newWord, new ArrayList<>())){
                    if(adjacentWord.equals(endWord)){
                        return level+1;
                    }
                    if(!visited.containsKey(adjacentword)){
                        visited.put(adjacentWord,true);
                        Q.add(new Pair(adjacentWord,level+1));
                    }
                }
                
            }
        }
        return 0;
    }
}

参考
leetcode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值