标签:style blog http io ar color os sp for
给定两个字符串start和end,和一个字符串字典dict,判断从start到end 要经过几次变化,每次变化只能取字典里的词,且相邻的变化只有一个字符不同。例如:
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.
Note:
class Solution { public: int ladderLength(string start, string end, unordered_set<string> &dict) { if (dict.size() == 0 || start == end) return 0; if (start.size() != end.size()) return 0; queue<string> que; que.push(start); que.push(""); int dis = 1; while(!que.empty()) { string str = que.front(); que.pop(); if (str != "") { for (int i = 0; i < str.size(); ++i) { for (char j = ‘a‘; j < ‘z‘; ++j) { if (j == str[i]) continue; char tmp = str[i]; str[i] = j; if (str == end) return dis + 1; if (dict.count(str) > 0) { dict.erase(str); que.push(str); } str[i] = tmp; } } } else if (!que.empty()) { que.push(""); dis++; } } return 0; } };
以上做法中需要对push到que中的字符串要在dic中删除,否则会死循环。
网上有提出两个que的,还要swap,觉得比上面的麻烦。不过思路应该是一致的。
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/higerzhang/p/4143849.html