- 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
- 51 lines of C++ from the credited upstream file 936.cpp.
- The implementation visibly relies on sequence storage.
- 3 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 vector<int> movesToStamp(string stamp, string target) {4 vector<int> ans;5 6 vector<bool> stamped(target.length());7 int stampedCount = 0; 8 9 while (stampedCount < target.length()) {10 bool isStamped = false;11 12 for (int i = 0; i <= target.length() - stamp.length(); ++i) {13 if (stamped[i])14 continue;15 const int stampified = stampify(stamp, target, i);16 if (stampified == 0)17 continue;18 stampedCount += stampified;19 isStamped = true;20 stamped[i] = true;21 ans.push_back(i);22 }23 24 if (!isStamped)25 return {};26 }27 28 ranges::reverse(ans);29 return ans;30 }31 32 private:33 34 35 36 int stampify(const string& stamp, string& target, int s) {37 int stampified = stamp.length();38 39 for (int i = 0; i < stamp.length(); ++i)40 if (target[s + i] == '*') 41 --stampified;42 else if (target[s + i] != stamp[i])43 return 0; 44 45 if (stampified > 0)46 fill(target.begin() + s, target.begin() + s + stamp.length(), '*');47 48 return stampified;49 }50};51