-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0936-stamping-the-sequence.js
More file actions
74 lines (66 loc) · 2.11 KB
/
0936-stamping-the-sequence.js
File metadata and controls
74 lines (66 loc) · 2.11 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Stamping The Sequence
* Time Complexity: O(T^2 * S)
* Space Complexity: O(T)
*/
var movesToStamp = function (stamp, target) {
const stampPatternLength = stamp.length;
const sequenceGoalLength = target.length;
const resultIndices = [];
const modifiedTargetChars = target.split("");
let currentQuestionMarkCount = 0;
const maximumAllowedTurns = 10 * sequenceGoalLength;
const evaluateAndPerformStamp = (startingPosition) => {
let segmentHasActualCharacters = false;
let isMatchPossible = true;
let examinationIndex = 0;
while (examinationIndex < stampPatternLength) {
const currentTargetCharacter =
modifiedTargetChars[startingPosition + examinationIndex];
const currentStampCharacter = stamp[examinationIndex];
if (currentTargetCharacter === "?") {
} else if (currentTargetCharacter === currentStampCharacter) {
segmentHasActualCharacters = true;
} else {
isMatchPossible = false;
break;
}
examinationIndex++;
}
if (!isMatchPossible || !segmentHasActualCharacters) {
return false;
}
let replacementIndex = 0;
while (replacementIndex < stampPatternLength) {
if (modifiedTargetChars[startingPosition + replacementIndex] !== "?") {
modifiedTargetChars[startingPosition + replacementIndex] = "?";
currentQuestionMarkCount++;
}
replacementIndex++;
}
return true;
};
let didMakeAnyProgress = true;
while (
currentQuestionMarkCount < sequenceGoalLength &&
didMakeAnyProgress &&
resultIndices.length <= maximumAllowedTurns
) {
didMakeAnyProgress = false;
let currentScanPosition = 0;
const maxScanPosition = sequenceGoalLength - stampPatternLength;
while (currentScanPosition <= maxScanPosition) {
if (evaluateAndPerformStamp(currentScanPosition)) {
resultIndices.push(currentScanPosition);
didMakeAnyProgress = true;
currentScanPosition = -1;
}
currentScanPosition++;
}
}
if (currentQuestionMarkCount === sequenceGoalLength) {
return resultIndices.reverse();
} else {
return [];
}
};