[LeetCode] Stamping The Sequence

936. Stamping The Sequence

You want to form a target string of lowercase letters.

At the beginning, your sequence is target.length ‘?’ marks. You also have a stamp of lowercase letters.

On each turn, you may place the stamp over the sequence, and replace every letter in the sequence with the corresponding letter from the stamp. You can make up to 10 * target.length turns.

For example, if the initial sequence is “?????”, and your stamp is “abc”, then you may make “abc??”, “?abc?”, “??abc” in the first turn. (Note that the stamp must be fully contained in the boundaries of the sequence in order to stamp.)

If the sequence is possible to stamp, then return an array of the index of the left-most letter being stamped at each turn. If the sequence is not possible to stamp, return an empty array.

For example, if the sequence is “ababc”, and the stamp is “abc”, then we could return the answer [0, 2], corresponding to the moves “?????” -> “abc??” -> “ababc”.

Also, if the sequence is possible to stamp, it is guaranteed it is possible to stamp within 10 * target.length moves. Any answers specifying more than this number of moves will not be accepted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
vector<int> movesToStamp(string stamp, string target) {
unordered_map<int, string> partial;
vector<int> res;
int part = 0;
bool flag = true;
string replaceStr(stamp.size(), '?');
for(int sz = stamp.size(); sz; sz--) {
for(int i = 0; i <= stamp.size() - sz; i++) {
partial[part++] = string(i, '?') + stamp.substr(i, sz) + string(stamp.size() - sz - i, '?');
}
}
while(flag) {
flag = false;
for(int i = 0; i < part; i++) {
auto pos = target.find(partial[i]);
while(pos != std::string::npos) {
flag = true;
res.push_back(pos);
target.replace(pos, stamp.length(), replaceStr);
cout<<target<<endl;
pos = target.find(partial[i], pos + 1);
}
}
}
for(int i = 0; i < target.length(); i++)
if(target[i] != '?')
return vector<int>();
reverse(res.begin(), res.end());
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/31/PS/LeetCode/stamping-the-sequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.