word-ladder(字梯)

1.题目

  给定两个单词(开始和结束)和一个字典,从头到尾查找最短变换序列的长度,以便:
一次只能更改一个字母,每个中间词必须存在于词典中
例如,给定:
start ="hit"
end ="cog"
dict =["hot","dot","dog","lot","log"]
由于最短的一个转换是"hit" -> "hot" -> "dot" -> "dog" -> "cog",所以返回5。

2.分析过程

     深度优先遍历的应用,当然也可以是广度优先遍历。

3.代码实现

import java.util.*;
public class Solution {
    public int ladderLength(String start, String end, HashSet<String> dict) {
        if(start==null || start.length()==0 || end==null || end.length()==0 || start.length()!=end.length())
            return 0;
        if(isSimlary(start,end)){
            return 2;
        }else{
            if(dict==null || dict.size()==0){
                return 0;
            }
        }
        Queue<String> queue=new LinkedList<>();
        HashSet<String> set=new HashSet<>();
        set.addAll(dict);
        queue.offer(start);
        int res=1;
        while(!queue.isEmpty()){
            set.removeAll(queue);
            int size=queue.size();
            while(size>0){
                String str=queue.poll();
                for(Iterator<String> it=set.iterator();it.hasNext();){
                    String temp=it.next();
                    if(isSimlary(str,temp)){
                        if(isSimlary(temp,end)){
                            return res+2;
                        }else{
                            queue.offer(temp);
                        }
                    }
                }
                size--;
            }
            res++;
        }
        return 0;
    }
    public boolean isSimlary(String start,String end){
        int count=0;
        for(int i=0;i<start.length();i++){
            if(start.charAt(i)!=end.charAt(i))
                 count++;
        }
        if(count==1) return true;
        else return false;
    }
}

题目来自牛客网leetcode

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值