Skip to content

Instantly share code, notes, and snippets.

@mitulmanish
Created July 13, 2016 03:23
Show Gist options
  • Save mitulmanish/4f987c3534dab9d012de8f8a2e8f30ac to your computer and use it in GitHub Desktop.
Save mitulmanish/4f987c3534dab9d012de8f8a2e8f30ac to your computer and use it in GitHub Desktop.
Character pattern matching Algorithm
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
char [] charSet = new char[] {'g', 'a', 't', 't', 'a', 'c', 'a', 'g', 'g', 'a',
't', 'a', 't', 'a', 'c','t','m', 'o', 'k', 't', 'a', 'c', 'h','t', 'g',
'k', 't', 'a', 'c', 'm', 'i', 't', 'u', 'l'};
char [] searchQuery = new char[] { 'm', 'i', 't', 'u', 'l' };
System.out.println(patternMatching(charSet, searchQuery));
}
private static int patternMatching(char[] charSet, char[] searchQuery) {
int counter = 0;
for(int i = 0; i < charSet.length; i++) {
int searchIndex = 0;
if (searchQuery[searchIndex] == charSet[i]) {
// if the first character of the search query matches with the current index of the
// char set , then we progress and match the next character of the search query with the next available
// character in the char set
int localCounter = 1;
int captureMatchingIndex = i + 1;
searchIndex ++;
while(searchIndex < searchQuery.length &&
captureMatchingIndex < charSet.length &&
searchQuery[searchIndex] == charSet[captureMatchingIndex]) {
captureMatchingIndex ++;
searchIndex ++;
localCounter ++;
}
if (localCounter == searchQuery.length) counter++;
}
}
return counter;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment