• [itint5]单词变换


    http://www.itint5.com/oj/#42

    基本上就是word ladder。直接来BFS,记录前驱。

    vector<string> transform(set<string> &dict, string from, string to) {
        vector<string> ans;
        if (from.length() != to.length()) {
            return ans;
        }
        queue<string> que;
        map<string, string> prev_map;
        que.push(from);
        prev_map[from] = "";
        while (!que.empty()) {
            string s = que.front();
            que.pop();
            if (s == to) break;
            for (int i = 0; i < s.length(); i++) {
                char tmp = s[i];
                for (char c = 'A'; c <= 'Z'; c++) {
                    if (tmp == c) continue;
                    s[i] = c;
                    if (dict.find(s) != dict.end()
                        && prev_map.find(s) == prev_map.end()) {
                        que.push(s);
                        prev_map[s] = s;
                        prev_map[s][i] = tmp;
                    }
                }
                s[i] = tmp;
            }
        }
        if (prev_map.find(to) == prev_map.end()) return ans;
        string last = to;
        do {
            ans.push_back(last);
            last = prev_map[last];
        } while (last != "");
        for (int i = 0; i < ans.size() / 2; i++) {
            int k = ans.size() - i - 1;
            string tmp = ans[i];
            ans[i] = ans[k];
            ans[k] = tmp;
        }
        return ans;
    }
    

      

  • 相关阅读:
    字典生成式
    三元表达式
    迭代器
    装饰器
    闭包函数
    名称空间和作用域
    函数嵌套
    SQL Server 影响dbcc checkdb的 8 种因素
    SQL Server 对dbcc checkdb的优化
    SQL Server dbcc checkdb 修复
  • 原文地址:https://www.cnblogs.com/lautsie/p/3526377.html
Copyright © 2020-2023  润新知