|
|
back to boardSolution using Z-function is O(n) but gives TLA Posted by Anton 13 Apr 2023 23:25 Unexpected result: the solution using z-function is O(n) but gives TLA on the 8th test. The solution doesn't pass so I will leave the code with it here. I'm wondering if it really doesn't pass the 8th test because it is too slow though is O(n), or if there's just some kind of error in my algorithm. vi ZFunction(string &p, string &s) { int n = (int) p.size(); vector<int> z(n + 1); for (int i = 0, l = 0, r = 0; i < n; ++i) { if (i <= r) z[i] = min(r - i + 1, z[i - l]); while (i + z[i] < n && p[z[i]] == s[i + z[i]]) ++z[i]; if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1; } return z; } .... vector<int> z_func = ZFunction(s1, s2); vector<int> z_func2 = ZFunction(s2, s1); for (int i = 0; i < n; ++i) { if (z_func[i] == n - i && z_func2[n - i] == i) { cout << i; return; } } cout << "-1"; Edited by author 13.04.2023 23:25 Edited by author 13.04.2023 23:25 Edited by author 13.04.2023 23:27 |
|
|