跳转至

戳印序列⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    vector<int> movesToStamp(string stamp, string target) {
        int m = stamp.size(), n = target.size();
        vector<int> inDegree(n - m + 1, m);
        vector<vector<int>> edges(n);
        queue<int> q;

        for (int i = 0; i < n - m + 1; i++) {
            for (int j = 0; j < m; j++) {
                if (target[i + j] == stamp[j]) {
                    if (--inDegree[i] == 0)
                        q.push(i);
                } else {
                    edges[i + j].push_back(i);
                }
            }
        }

        vector<bool> seen(n, false);
        vector<int> res;
        while (!q.empty()) {
            int current = q.front();
            q.pop();
            res.push_back(current);

            for (int i = 0; i < m; i++) {
                if (!seen[current + i]) {
                    seen[current + i] = true;
                    for (auto&& edge : edges[current + i]) {
                        if (--inDegree[edge] == 0)
                            q.push(edge);
                    }
                }
            }
        }

        if (res.size() < n - m + 1)
            return {};
        reverse(res.begin(), res.end());
        return res;
    }
};