标签:lis int class str tin ring eve png alt
class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> words; for(auto &s:wordList){ words.insert(s); } if(words.find(endWord)==words.end()) return 0; unordered_set<string> beginSet; unordered_set<string> endSet; beginSet.insert(beginWord); endSet.insert(endWord); unordered_set<string> visited; visited.insert(beginWord); visited.insert(endWord); int level=1; while(!beginSet.empty() && !endSet.empty()){ if(beginSet.size()>endSet.size()){ auto tmp=beginSet; beginSet=endSet; endSet=tmp; } unordered_set<string> tmp; for(auto s:beginSet){ for(int i=0;i<s.size();++i){ char bk=s[i]; for(char c=‘a‘;c<=‘z‘;++c){ if(c==bk) continue; s[i]=c; if(endSet.find(s)!=endSet.end()) return level+1; if(visited.find(s)==visited.end() && words.find(s)!=words.end()){ visited.insert(s); tmp.insert(s); } } s[i]=bk; } } beginSet=tmp; ++level; } return 0; } };
LC 127. Word Ladder (two end bfs)
标签:lis int class str tin ring eve png alt
原文地址:https://www.cnblogs.com/FEIIEF/p/12286268.html