[leetcode]127 Word Ladder BFS

要maintain的量:

int level, Queue curLevel, Queue nextLevel, Set visited

两个check curLevel 的loop,里面对每个char position进行从a-z的调换,查1)是不是end, 是就return level+1;   2) 在dict, 没在visited就加nextLevel

要注意的地方:

1) 找到了return level+1 (根据题目要求)

2)走到跟original word一样的case要跳过

3)visited在加nextlevel的时候就加,不然会有重复

4)里面loop结束要把arr[i]换回原来的 (因为arr initiate在外面,如果在里面就无所谓)

5)edge case (start.equals(end)) 要return 1;


public class Solution {

    public int ladderLength(String start, String end, Set<String> dict) {
        if (start==null||end==null||start.length()!=end.length()||dict==null) return 0;
        int level = 1;
        if (start.equals(end)) return 1;
        Queue<String> curLevel = new LinkedList<String>();
        Queue<String> nextLevel = new LinkedList<String>();
        HashSet<String> visited = new HashSet<String>();
        curLevel.add(start);
        visited.add(start);
        while (!curLevel.isEmpty()) {
            while (!curLevel.isEmpty()) {
                String cur = curLevel.remove();
                char[] arr = cur.toCharArray();
                for (int i=0;i<arr.length;i++) {
                    for (char c='a';c<='z';c++) {
                        if (c==cur.charAt(i)) continue;
                        arr[i]=c;
                        String item = new String(arr);
                        if (item.equals(end)) return level+1;
                        if (dict.contains(item)&&!visited.contains(item)) {
                        nextLevel.add(item);
                        visited.add(item);
                    }
                }
                arr[i]=cur.charAt(i);
            }
            }
            level++;
            curLevel = nextLevel;
            nextLevel = new LinkedList<String>();
        }
        return 0;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值