单词转化

word-ladder

http://www.nowcoder.com/questionTerminal/bd75ae43ff7148548eb4701550df2714

没做过这种图论的题目,一脸懵逼😳,看了大佬的解析,自己再总结(fushu)一遍:

将所有路径表示出来——

        ->lot->log
hit->hot          ->cog
        ->dot->dog

这个其实就是求图论中的单源最短路径,图中边是没有权重的,用BFS求解最合适(时间复杂度O(n))。

class Solution {
public:
    int ladderLength(string start, string end, unordered_set &dict) {
        queue> record;
        record.push(make_pair(start, 1));
        while (!record.empty()) {
            pair current = record.front();
            record.pop();
            if (current.first == end) {
                return current.second;
            }
            // 替换每一个字符,并在set中搜寻
            for (int i = 0; i < current.first.size(); ++i) {
                for (int j = 0; j < 26; ++j) {
                    string str = current.first;
                    str[i] = 'a' + j;
                    if (dict.find(str) != dict.end()) {
                        record.push(make_pair(str, current.second+1));
                        dict.erase(str);
                    }
                }
            }
        }
        return 0;
    }
};
刷遍天下无敌手 文章被收录于专栏

秋招刷题历程

全部评论

相关推荐

04-27 08:59
常州大学 Java
牛客139242382号:《两门以上汇编语言》
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务