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 };

 

posted on 2015-03-25 09:20  keepshuatishuati  阅读(127)  评论(0编辑  收藏  举报