import java.util.ArrayList;
import java.util.Stack;
public class StackImplementation {
class Data {
ArrayList<Integer> present;
int count;
public Data(ArrayList<Integer> present, int count)
{
this.present = present;
this.count = count;
}
}
public Data Solution(char pattern[], char text[])
{
ArrayList<Integer> list = new ArrayList<>();
Stack<String> stack = new Stack<>();
int p = 0;
int counter = 0;
int lastOccurrence = -10;
for (int i = 0; i < text.length; i++) {
if (text[i] == pattern[p]) {
if (text[i]
== pattern[pattern.length - 1]) {
list.add(i);
counter++;
lastOccurrence = i;
p = 0;
}
else {
p++;
}
}
else {
if (text[i] == pattern[0]) {
String temp = "";
for (int i1 = p; i1 < pattern.length;
i1++)
temp += pattern[i1];
stack.push(temp);
p = 1;
}
else {
if (lastOccurrence == i - 1) {
if (stack.isEmpty())
p = 0;
else {
String temp = stack.pop();
if (temp.charAt(0) == text[i]) {
lastOccurrence = i;
if (temp.charAt(0)
== pattern[pattern
.length
- 1]) {
list.add(i);
counter++;
}
else {
temp = temp.substring(
1, temp.length());
stack.push(temp);
}
}
else {
if (!stack.isEmpty())
stack.clear();
p = 0;
}
}
}
else {
if (!stack.isEmpty())
stack.clear();
p = 0;
}
}
}
}
return new Data(list, counter);
}
public static void main(String args[])
{
char[] pattern = "ABC".toCharArray();
char[] text = "ABABCABCC".toCharArray();
StackImplementation obj = new StackImplementation();
Data data = obj.Solution(pattern, text);
int count = data.count;
ArrayList<Integer> list = data.present;
System.out.println(count);
if (count > 0) {
System.out.println("Occurrences found at:");
for (int i : list)
System.out.print(i + " ");
}
}
}