Monday, 2 May 2016

What is Naïve String Matching Algorithm ?



  • A Brute force algorithm
  • identifies the presence of a pattern in the given text
  • Complexity of checking : O( (n-m)m )


Algorithm
char[] textArr = text.toCharArray();
char[] patternArr = pattern.toCharArray();

int textLen = textArr.length;
int paternLen = patternArr.length;

for (int i = 0; i < textLen - patternLen; i++) {
     int charMatchCount = 0;
     for (int j = 0; j < patternLen; j++) {
         /**
          * If pattern mismatch, break next searching point.
          **/
          if (patternArr[j] != textArr[i + j]) {
               break;
          }
          charMatchCount++;
     }

     // If all characters of pattern matched
     if (charMatchCount == patternLen) {
         System.out.println("String found at "+(i+1)+" position!!");
         break;
     }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.