Binary Pattern Search in Java

 You have a given two string pattern and s(word). The first string pattern contains only the symbols 0 and 1 and the second string s contains only lowercase english letters.

Lets's say that pattern matches a substring s[1..r] or s if the following 3 conditions are met:

  • they have equal length
  • for each 0 in pattern the corresponding letter in the substring is a vowel
  • for each 1 in pattern the corresponding letter is a consonant.
Your task is to calculate the number of substrings of s that match pattern.

Note: in this task we defines the vowels as 'a', 'e', 'i', 'o', 'u' and 'y'. All other letters are constants.

Here is the solutions:

public class Test {
public static void main(String[] args) {
String pattern = "010";
String s = "amazing";
System.out.println("Total no occurrences: " + countMatches(pattern, s));

private static int countMatches(String pattern, String s) {
int pLen = pattern.length();
int sLen = s.length();
int matches = 0, fromIndex = 0;
if( pLen != sLen) {
String fs = s.replaceAll("[aeiouy]", "0").replaceAll("[bcdfghjklmnpqrstvwxz]", "1");
while ((fromIndex = fs.indexOf(pattern, fromIndex)) != -1) {
return matches;

Output: Total occurrences: 2

Thanks and Enjoy !!!