Open In App

Count of occurrences of a “1(0+)1” pattern in a string

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

Examples: 

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: 

  1. 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. 
  2. 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: 

C++




// C++ program to calculate number of times
// the pattern occurred in given string
#include<iostream>
using namespace std;
 
// Returns count of occurrences of "1(0+)1"
// int str.
int countPattern(string str)
{
    int len = str.size();
    bool oneSeen = 0;
 
    int count = 0;  // Initialize result
    for (int i = 0; i < len ; i++)
    {
 
        // Check if encountered '1' forms a valid
        // pattern as specified
        if (str[i] == '1' && oneSeen == 1)
            if (str[i - 1] == '0')
                count++;
 
        // if 1 encountered for first time
        // set oneSeen to 1
        if (str[i] == '1' && oneSeen == 0)
           {
            oneSeen = 1;
            continue;
           }
        // Check if there is any other character
        // other than '0' or '1'. If so then set
        // oneSeen to 0 to search again for new
        // pattern
        if (str[i] != '0' && str[i] != '1')
            oneSeen = 0;
 
 
    }
 
    return count;
}
 
// Driver program to test above function
int main()
{
    string str = "100001abc101";
    cout << countPattern(str);
    return 0;
}


Java




//Java program to calculate number of times
//the pattern occurred in given string
public class GFG
{
    // Returns count of occurrences of "1(0+)1"
    // int str.
    static int countPattern(String str)
    {
        int len = str.length();
        boolean oneSeen = false;
         
        int count = 0// Initialize result
        for(int i = 0; i < len ; i++)
        {
            char getChar = str.charAt(i);
             
            // Check if encountered '1' forms a valid
            // pattern as specified
            if (getChar == '1' && oneSeen == true){
                if (str.charAt(i - 1) == '0')
                    count++;
            }
 
            // if 1 encountered for first time
            // set oneSeen to 1
            if(getChar == '1' && oneSeen == false)
                oneSeen = true;
             
            // Check if there is any other character
            // other than '0' or '1'. If so then set
            // oneSeen to 0 to search again for new
            // pattern
            if(getChar != '0' && str.charAt(i) != '1')
                oneSeen = false;
             
 
        }
        return count;
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
         String str = "100001abc101";
         System.out.println(countPattern(str));
    }
 
}
// This code is contributed by Sumit Ghosh


Python3




# Python program to calculate number of times
# the pattern occurred in given string
 
# Returns count of occurrences of "1(0+)1"
def countPattern(s):
    length = len(s)
    oneSeen = False
     
    count = 0   # Initialize result
    for i in range(length):
 
        # Check if encountered '1' forms a valid
        # pattern as specified
        if (s[i] == '1' and oneSeen):
            if (s[i - 1] == '0'):
                count += 1
 
        # if 1 encountered for first time
        # set oneSeen to 1
        if (s[i] == '1' and oneSeen == 0):
            oneSeen = True
  
        # Check if there is any other character
        # other than '0' or '1'. If so then set
        # oneSeen to 0 to search again for new
        # pattern
        if (s[i] != '0' and s[i] != '1'):
            oneSeen = False
  
 
  
    return count
 
# Driver code
s = "100001abc101"
print(countPattern(s))
 
# This code is contributed by Sachin Bisht


C#




// C# program to calculate number
// of times the pattern occurred
// in given string
using System;
 
class GFG
{
// Returns count of occurrences
// of "1(0+)1" int str.
public static int countPattern(string str)
{
    int len = str.Length;
    bool oneSeen = false;
 
    int count = 0; // Initialize result
    for (int i = 0; i < len ; i++)
    {
        char getChar = str[i];
 
        // Check if encountered '1' forms
        // a valid pattern as specified
        if (getChar == '1' &&
                 oneSeen == true)
        {
            if (str[i - 1] == '0')
            {
                count++;
            }
        }
 
        // if 1 encountered for first
        // time set oneSeen to 1
        if (getChar == '1' &&
            oneSeen == false)
        {
            oneSeen = true;
        }
 
        // Check if there is any other character
        // other than '0' or '1'. If so then set
        // oneSeen to 0 to search again for new
        // pattern
        if (getChar != '0' &&
                 str[i] != '1')
        {
            oneSeen = false;
        }
 
 
    }
    return count;
}
 
// Driver Code
public static void Main(string[] args)
{
    string str = "100001abc101";
    Console.WriteLine(countPattern(str));
}
 
}
 
// This code is contributed
// by Shrikant13


PHP




<?php
// PHP program to calculate number of times
// the pattern occurred in given string
 
// Returns count of occurrences
// of "1(0+)1"
function countPattern($str)
{
    $len = strlen($str);
    $oneSeen = 0;
 
    $count = 0; // Initialize result
    for ($i = 0; $i < $len ; $i++)
    {
        // Check if encountered '1' forms a
        // valid pattern as specified
        if ($str[$i] == '1' && $oneSeen == 1)
            if ($str[$i - 1] == '0')
                $count++;
 
        // if 1 encountered for first
        // time set oneSeen to 1
        if ($str[$i] == '1' && $oneSeen == 0)
            $oneSeen = 1;
 
        // Check if there is any other character
        // other than '0' or '1'. If so then set
        // oneSeen to 0 to search again for new
        // pattern
        if ($str[$i] != '0' && $str[$i] != '1')
            $oneSeen = 0;
 
 
    }
 
    return $count;
}
 
// Driver Code
$str = "100001abc101";
echo countPattern($str);
 
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
//Javascript program to calculate number of times
//the pattern occurred in given string
     
    // Returns count of occurrences of "1(0+)1"
    // int str.
    function countPattern(str)
    {
        let len = str.length;
        let oneSeen = false;
           
        let count = 0;  // Initialize result
        for(let i = 0; i < len ; i++)
        {
            let getChar = str[i];
               
            // Check if encountered '1' forms a valid
            // pattern as specified
            if (getChar == '1' && oneSeen == true){
                if (str[i-1] == '0')
                    count++;
            }
   
            // if 1 encountered for first time
            // set oneSeen to 1
            if(getChar == '1' && oneSeen == false)
                oneSeen = true;
               
            // Check if there is any other character
            // other than '0' or '1'. If so then set
            // oneSeen to 0 to search again for new
            // pattern
            if(getChar != '0' && str[i] != '1')
                oneSeen = false;
               
   
        }
        return count;
    }
     
    // Driver program to test above function
    let str = "100001abc101";
    document.write(countPattern(str));
     
    //This code is contributed by avanitrachhadiya2155
     
</script>


Output

2

Time Complexity: O( N ), where N is the length of input string.
Auxiliary Space: O(1), as extra space is not required

If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org.  



Last Updated : 15 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads