Examples of Java data structures and algorithms: naive characters match Brute Force
- 2020-04-01 03:56:59
- OfStack
package al;
public class BruteForce {
public static void main(String[] args) {
String waitForMatch = "abbacbabcdabcbec";
String pattern = "abcbe";
BruteForce bruteForce = new BruteForce();
int index = bruteForce.getSubStringIndex(waitForMatch, pattern);
System.out.println("Matched index is "+index);
}
public int getSubStringIndex(String waitForMatch, String pattern){
int stringLength = waitForMatch.length();
int patternLength = pattern.length();
//Start with the main string
for(int i=0; i<stringLength; i++) {
int k = i; //K points to the next position in the main string
for(int j=0; j<patternLength; j++) {
if(waitForMatch.charAt(k) != pattern.charAt(j)) {
break;
}else {
k++;//Points to the next position in the main string
if(j == patternLength-1) {
return i;
}
}
}
}
//An unsuccessful match returns 0
return 0;
}
}