• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Word Ladder

直接看答案。。

 1 class Solution {
 2 public:
 3     int ladderLength(string start, string end, unordered_set<string> &dict) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (start.size() != end.size() || !dict.size()) return 0;
 7         int dis = 1;
 8         queue<string> queTopush, queTopop;
 9         queTopop.push(start);
10         while (dict.size() && !queTopop.empty()) {
11             while (!queTopop.empty()) {
12                 string str = queTopop.front();
13                 queTopop.pop();
14                 for (int i = 0; i < str.size(); i++) {
15                     for (char j = 'a'; j <= 'z'; j++) {
16                         if (j == str[i]) continue;
17                         char tmp = str[i];
18                         str[i] = j;
19                         if (str == end) return dis+1;
20                         if (dict.count(str)) {
21                             queTopush.push(str);
22                             dict.erase(str);
23                         }
24                         str[i] = tmp;
25                     }
26                 }
27             }
28             queTopop.swap(queTopush);
29             dis++;
30         }
31         return 0;
32     }
33 };

 

posted @ 2013-04-23 02:29  ying_vincent  阅读(199)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3