Count patterns that start and end with "1", with 0's in between A string contains many patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0's. The patterns are allowed to overlap.

For example, consider string "1101001", we can see there are two consecutive sequences "1(0)1" and "1(00)1" which are of the form 1(0+)1.



public class Solution {

        static int patternCount(String s){
            String[] sArray = s.split("1");
            for(String str : sArray) {
                if(Pattern.matches("[0]+", str)) {
                    count++;
                }
            }
            return count;
        }

        public static void main(String[] args) {
            int result = patternCount("1001010001");
            System.out.println(result);//3
        }
    }


Sample Input:

100001abc101, 1001ab010abc01001, 1001010001


Sample Output:

2 2 3


But still something i feel might fail in future could you please help me to optimize my code as per the Requirement
Although the other 2 answers currently given are technically correct. I find it more logical to search for a 1 followed by any number of 0's ending with another 1 which we cannot consume yet (as it can be used again in the following match).

So the pattern should look like 1[0]+(?=1)

Which turns the method implementation to this:

static int patternCount(String s) {
    Pattern pattern = Pattern.compile("1[0]+(?=1)");
    Matcher matcher = pattern.matcher(s);
    int count = 0;
    while (matcher.find()) {
        count++;
    }
    return count;
}