- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 49 lines of C++ from the credited upstream file 3455.cpp.
- The implementation visibly relies on sequence storage.
- 6 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int shortestMatchingSubstring(string s, string p) {4 const auto [a, b, c] = split(p);5 const int ns = s.length();6 const int na = a.length();7 const int nb = b.length();8 const int nc = c.length();9 const vector<int> lpsA = getLPS(a + '#' + s);10 const vector<int> lpsB = getLPS(b + '#' + s);11 const vector<int> lpsC = getLPS(c + '#' + s);12 int ans = INT_MAX;13 14 for (int i = 0, j = 0, k = 0; i + nb + nc < ns; ++i) {15 while (i < ns && lpsA[na + 1 + i] != na)16 ++i;17 while (j < ns && (j < i + nb || lpsB[nb + 1 + j] != nb))18 ++j;19 while (k < ns && (k < j + nc || lpsC[nc + 1 + k] != nc))20 ++k;21 if (k == ns)22 break;23 ans = min(ans, k - i + na);24 }25 26 return ans == INT_MAX ? -1 : ans;27 }28 29 private:30 31 32 vector<int> getLPS(const string& pattern) {33 vector<int> lps(pattern.length());34 for (int i = 1, j = 0; i < pattern.length(); ++i) {35 while (j > 0 && pattern[j] != pattern[i])36 j = lps[j - 1];37 if (pattern[i] == pattern[j])38 lps[i] = ++j;39 }40 return lps;41 }42 43 tuple<string, string, string> split(const string& p) {44 const int i = p.find('*');45 const int j = p.find('*', i + 1);46 return {p.substr(0, i), p.substr(i + 1, j - i - 1), p.substr(j + 1)};47 }48};49