classSolution { public: boolisMatch(string s, string p){ if (s.length() == 0 && std::all_of(p.begin(), p.end(), [](char c) { return c == '*'; })) returntrue; if (p.length() == 0) returnfalse;
int sn = s.length(); int pn = p.length(); dp[0][0] = 1; for (int i = 1; i <= pn; ++i) { dp[0][i] = std::all_of(p.begin(), p.begin() + i, [](char c) { return c == '*'; }); } for (int i = 1; i <= sn; ++i) { dp[i][0] = false; } for (int i = 1; i <= sn; ++i) { for (int j = 1; j <= pn; ++j) {
在贪心方法中,对于每一个被星号分隔的、只包含小写字符和问号的子模式 ,我们在原串中使用的是暴力匹配的方法。然而这里是可以继续进行优化的,即使用 AC 自动机 代替暴力方法进行匹配。 由于 AC 自动机本身已经是竞赛难度的知识点,而本题还需要在 AC 自动机中额外存储一些内容才能完成匹配,因此这种做法远远超过了面试难度。 这里只给出参考讲义 Set Matching and Aho-Corasick Algorithm:
讲义的前 6 页介绍了字典树 Trie;
讲义的 7−19 页介绍了 AC 自动机,它是以字典树为基础的;
讲义的 20−23 页介绍了基于 AC 自动机的一种 wildcard matching 算法,其中的 wildcard 就是本题中的问号。
Related Issues not found
Please contact @XChy to initialize the comment