LeetCode – Refresh – Word Ladder

Do the BFS and use a hashset to record whether the word has been found before.

 1 class Solution {
 2 public:
 3     int ladderLength(string start, string end, unordered_set<string> &dict) {
 4         int len = start.size();
 5         if (len == 0 || len != end.size()) return 0;
 6         queue<string> q;
 7         q.push(start);
 8         unordered_set<string> record;
 9         int current = 1, future = 0, level = 1;
10         while (!q.empty()) {
11             string str = q.front();
12             q.pop(), current--;
13             for (int i = 0; i < len; i++) {
14                 string tmp = str;
15                 for (char c = 'a'; c <= 'z'; c++) {
16                     tmp[i] = c;
17                     if (tmp == end) return level+1;
18                     if (record.find(tmp) == record.end() && dict.find(tmp) != dict.end()) {
19                         record.insert(tmp);
20                         q.push(tmp);
21                         future++;
22                     }
23                 }
24             }
25             if (!current) {
26                 current = future;
27                 future = 0;
28                 level++;
29             }
30         }
31     }
32 };

 

转载于:https://www.cnblogs.com/shuashuashua/p/4364710.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值