Pattern Occurrences : Stack Implementation Java
Suppose we have two Strings :- Pattern and Text
pattern: consisting of unique characters
text: consisting of any length
We need to find the number of patterns that can be obtained from text removing each and every occurrence of Pattern in the Text.
Input : Pattern : ABC Text : ABABCABCC Output : 3 Occurrences found at: 4 7 8 Explanation Occurrences and their removal in the order 1. ABABCABCC 2. ABABCC 3. ABC
The idea is to use stack data structure.
1. Initialize a pointer to beginning for matching the occurrences in the pattern with 0 and counter to 0.
2. Check if pattern and text have same character at the present index.
3. If the pointer is to the end of pattern that means all the previous characters have been found in an increasing subsequential order increment the counter by 1.
4. If not, keep incrementing the pointer by 1 if characters are same.
5. If the characters are different in both the strings, check if the character is same as the first character of the pattern (i.e. pointer = 0).
6. If yes, add the remaining characters from the present pointer to length of the pattern to a stack and check if they are present in order that the pattern can be formed from the stack. Also, initialize the pointer now to 1 because we already had checked for pointer = 0 (in step 5).
7. If matches, empty the stack to null. Else, remove the first character and keep adding the rest of the substring for checking for further of the steps.
8. If any added String to the Stack matches the pattern increment counter by 1 and initialize pointer by 0.
9. Repeat all these steps for all the indexes of the text length.
10. Print the counter and occurrences.
11. Basic task of Stack is handling the pending operations that might be possible occurrences.
Example Explanation according to above algorithm:
TEXT: ABABCABCC PATTERN: ABC pointer = 0 counter = 0 A B A B C A B C C 0 1 2 3 4 5 6 7 8 at index = 0 pointer = 0 stack =  at index = 1 pointer = 1 stack =  at index = 2 pointer = 0 stack = ['C'] at index = 3 pointer = 1 stack = ['C'] at index = 4 pointer = 2 counter += 1 pointer = 0 stack = ['C'] same for index 5,6,7 according to above method at index = 8 pop from Stack counter += 1 clear Stack
Code in Java for the algorithm:
Prerequisite : Stack class in Java
3 Occurrences found at: 4 7 8
1. Stack Java Documentation.
2. Custom ArrayList and Class in Java.
3. More on Stack Operations.
This article is contributed by Shubham Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.