2
public int[] movesToStamp(String stamp, String target) {6
* Instead of creating target string from intial state,7
* create the intial state from the target string.8
* - take a window of stamp length9
* - reverse that window to the intail state10
* current state -> abcdefgh, window = def,11
* next state -> abc???gh15
int sLen = stamp.length();16
int tLen = target.length();18
// it save the index of reversed charcacter19
Queue<Integer> reversedCharIndices = new LinkedList();21
// it mark Character of target, as reversed22
boolean[] isReversedCharOfThisIndex = new boolean[tLen];24
Stack<Integer> stack = new Stack();26
List<Window> widowList = new ArrayList();28
for (int windowStartIndex = 0; windowStartIndex <= tLen - sLen; windowStartIndex++) {30
Set<Integer> matched = new HashSet();31
Set<Integer> notMatched = new HashSet();33
for (int j = 0; j < sLen; j++) {35
// char index of current window of the target36
int charIndex = windowStartIndex + j;38
if (stamp.charAt(j) == target.charAt(charIndex)) {39
matched.add(charIndex);41
notMatched.add(charIndex);46
widowList.add(new Window(matched, notMatched));48
// when all char of current window is matched with49
if (notMatched.isEmpty()) {50
stack.push(windowStartIndex);52
for (int index : matched) {53
if (!isReversedCharOfThisIndex[index]) {55
// add in queue, so that we can process,56
// another window which is affected by its character get reversed57
reversedCharIndices.add(index);60
isReversedCharOfThisIndex[index] = true;66
// get all char index, one by once67
// see the impact of reverse char of this index, in ano68
while (!reversedCharIndices.isEmpty()) {69
int reversedCharIndex = reversedCharIndices.remove();71
int start = Math.max(0, reversedCharIndex - sLen + 1);72
int end = Math.min(reversedCharIndex, tLen - sLen);74
for (int windowIndex = start; windowIndex <= end; windowIndex++) {76
if (widowList.get(windowIndex).notMatched.contains(reversedCharIndex)) {78
// as this char is reversed in another window79
// remove this char index from current window,80
widowList.get(windowIndex).notMatched.remove(reversedCharIndex);82
if (widowList.get(windowIndex).notMatched.isEmpty()) {84
// as all of charcater reversed of current window85
// now add current window index86
stack.push(windowIndex);88
for (int index : widowList.get(windowIndex).matched) {90
if (!isReversedCharOfThisIndex[index]) {92
// add in queue, so that we can process,93
// another window which is affected by its character get reversed94
reversedCharIndices.add(index);97
isReversedCharOfThisIndex[index] = true;105
for (boolean reversed : isReversedCharOfThisIndex) {112
int[] result = new int[stack.size()];113
while (!stack.empty()) {114
result[i++] = stack.pop();122
Set<Integer> matched;123
Set<Integer> notMatched;125
public Window(Set<Integer> matched, Set<Integer> notMatched) {126
this.matched = matched;127
this.notMatched = notMatched;