Developing the String Matching Algorithm in Java

The aim is to write a code in Java to apply a naive string matching algorithm.

We need to build the naive string matching algorithm. For this algorithm, we need to return all valid starting positions (or shifts) in the text T in which the pattern P occurs.

Perform the following steps:

  1. Implement the match() method of the NaiveStringMatching class, which
    available on GitHub at the following path:

    https://github.com/TrainingByPackt/Data-Structures-and-Algorithms-in-Java/blob/master/src/main/java/com/packt/datastructuresandalg/lesson5/activity/naivestringmatching/NaiveStringMatching.java
  2. Repeatedly shift pattern P along text T, matching all the characters in it with the characters aligned in T.
  3. When a match occurs, keep track of the index in T where it did.
The implementation of the naive string matching algorithm is an almost direct translation of the problem statement. We want to go through all possible shifts for P and check which ones are valid by comparing each element of P with the corresponding shifted elements of T.

A possible solution for this problem is in the following snippet:

for (int i = 0; i < n - m + 1; i++) {
boolean hasMatch = true;
for (int j = 0; j < m; j++) {
if (P.charAt(j) != T.charAt(i + j)) {
hasMatch = false;
break;
}
}
if (hasMatch)
shifts.add(i);
}
Snippet 5.1: Solution to the naive string matching problem. Source class name: solution.NaiveStringMatching

Go to https://goo.gl/PmEFws to access this code.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.179.100