Given an alphanumeric string, find the number of times a pattern 1(0+)1 occurs in the given string. Here, (0+) signifies the presence of non empty sequence of consecutive 0’s.
Input : 1001010001 Output : 3 First sequence is in between 0th and 3rd index. Second sequence is in between 3rd and 5th index. Third sequence is in between 5th and 9th index. So total number of sequences comes out to be 3. Input : 1001ab010abc01001 Output : 2 First sequence is in between 0th and 3rd index. Second valid sequence is in between 13th and 16th index. So total number of sequences comes out to be 2.
The idea to solve this problem is to first find a ‘1’ and keep moving forward in the string and check as mentioned below:
- If any character other than ‘0’ and ‘1’ is obtained then it means pattern is not valid. So we go on in the search of next ‘1’ from this index and repeat these steps again.
- If a ‘1’ is seen, then check for the presence of ‘0’ at previous position to check the validity of sequence.
Below is the implementation of above idea:
Time Complexity: O( N ), where N is the length of input string.
This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.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.
- Count occurrences of a string that can be constructed from another given string
- Count occurrences of a word in string
- Count occurrences of a sub-string with one variable character
- Count occurrences of a character in a repeated string
- Pattern Occurrences : Stack Implementation Java
- Occurrences of a pattern in binary representation of a number
- In-place replace multiple occurrences of a pattern
- Count occurrences of a substring recursively
- Replace all occurrences of pi with 3.14 in a given string
- Remove all occurrences of a character in a string
- Replace all occurrences of a string with space
- Check if a binary string has two consecutive occurrences of one everywhere
- Recursive program to replace all occurrences of pi with 3.14 in a given string
- Rearrange a binary string as alternate x and y occurrences
- Replace all occurrences of string AB with C without using extra space