LeetCode word-ladder-ii

题目描述


Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) 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"]

Return

  [
    ["hit","hot","dot","dog","cog"],
    ["hit","hot","lot","log","cog"]
  ]


Note:

  • All words have the same length.

  • All words contain only lowercase alphabetic characters.

这道题我并没有通过所有测试,在这里想分享一下我的思路

解题思路:

  • 建立一个队列,队列初始为start
  • 获取当前队列的size,循环poll 直到size = 0; 循环中判断是否当前结果的最后一个字符串与end差1距离
  • 如果是,则放入结果队列中,如果不是 从字典中查找每个只差1距离的字符的字符串,然后放入队列中。
import java.util.*;
public class Solution {
   	public ArrayList<ArrayList<String>> findLadders(String start, String end,
			HashSet<String> dict) {
		ArrayList<ArrayList<String>> reverse = new ArrayList<>();

		ArrayList<ArrayList<String>> res = new ArrayList<>();
		if (dict.contains(start)) {
			dict.remove(start);
		}
		LinkedList<ArrayList<String>> queue = new LinkedList<>();
		
		ArrayList<String> init = new ArrayList<>();
		init.add(start);
		queue.offer(init);
		boolean find = false;
		HashSet<String> removes = new HashSet<>();
		while (!queue.isEmpty() && !find) {
			int size = queue.size();
			removes.clear(); 
			while (size > 0) {
				ArrayList<String> cur = queue.poll();
				size--;
				String last = cur.get(cur.size() - 1);
				if (distance(last, end) == 1) {
					ArrayList<String> next = (ArrayList<String>) cur.clone();
					next.add(end);
					reverse.add(next);
					find = true;
				} else {
					
					for (Iterator<String> it = dict.iterator(); it.hasNext();) {
						String p = it.next();
						if (distance(p, last) == 1) {
							ArrayList<String> next = (ArrayList<String>) cur.clone();
							next.add(p);
							queue.offer(next);
							removes.add(p);
						}
					}
					
				}
				
			}
			for (Iterator<String>it = removes.iterator(); it.hasNext();) {
				dict.remove(it.next());
			}
		}
		for (int i = reverse.size() - 1; i >= 0; i--) {
			res.add(reverse.get(i));
		}
		return res;
	}

	public int distance(String p, String q) {
		int count = 0;
		for (int i = 0; i < p.length(); i++) {
			if (p.charAt(i) != q.charAt(i)) {
				count++;
			}
		}
		return count;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值