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:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start ="hit"
end ="cog"
dict =["hot","dot","dog","lot","log"]

As one shortest transformation is"hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

题意:

给定两个单词(start和end)和一个字典,找出从start到end的最短变换序列的长度,这样:

一次只能换一个字母

每个中间词都必须存在于字典中

例如,

start ="hit"
end ="cog"
dict =["hot","dot","dog","lot","log"]

一个最短的变换是“hit”—>“hot”—>“dot”—>“dog”—>“cog”,

返回其length5。

注意:

如果没有这样的转换序列,返回0。

所有的单词都有相同的长度。

所有单词只包含小写字母。

 

思路:

这题应该用BFS来解决。首先将start加入队列,然后取出队首字符串,对队首字符串置换一个字母,置换之后与end字符串进行比较,如果相同就返回result+1,不同就查询是否存在于dict中,如果有将其入队,同时在dict中删除(防止重复比较)。重复此流程直到队列为空。

 

代码:

public int ladderLength(String start, String end, HashSet<String> dict) {
		if(start ==null || end == null || dict == null) {
			return 0;
		}
		
		Queue<String>queue = new LinkedList<String>();
		int result = 1;
		//入队
		queue.offer(start);
		
		while(!queue.isEmpty()) {
			
			for(int k = queue.size(); k>0;k--) {
				//取队首值
				String str = queue.peek();
				//出队
				queue.poll();
				
				for(int i=0;i<str.length();i++) {
					char[] chs = str.toCharArray();
					//遍历字符串,置换字母
					for(char j ='a';j<'z';j++) {
						chs[i] = j;
						String tmp = new String(chs);
						//如果和end相等,返回结果
						if(tmp.equals(end)) {
							return result+1;
						}
						//如果存在于字典中,入队 同时在字典中删除此字符串,防止重复比较
						if(dict.contains(tmp)) {
							queue.offer(tmp);
							dict.remove(tmp);
						}
					}
					
				}
			}
			result++;
		}
		return 0;
        
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值