Brute force matching of Java pattern matching
- 2020-04-01 03:53:19
- OfStack
Brute force matching of Java pattern matching
package javay.util;
public class PMBF {
public static int patternMatch(String target, String pattern) {
int targetLength = target.length();
int patternLength = pattern.length();
int idxTgt = 0; //The position of a character in the target string
int idxPtn = 0; //The position of characters in a pattern string
int index = 0; //Saves the position of the starting character that matches ing to the pattern string
while(idxTgt < targetLength && idxPtn < patternLength) {
//Find a matching character
if(target.charAt(idxTgt) == pattern.charAt(idxPtn)) {
//If they are equal, a subsequent comparison of the characters continues
idxTgt ++;
idxPtn ++;
} else {
//Otherwise the target string starts from the second character and is recompared to the first character of the pattern string
index ++;
idxPtn = 0;
idxTgt = index;
}
}
//Match to one, output the result
if(idxPtn == patternLength) {
//Indicating a successful match
return index;
} else {
return -1;
}
}
}
Examples of use:
static int indexOf(char[] source,char[] target) {
char first = target[0];
int max = (source.length - target.length);
for (int i = 0; i <= max; i++) {
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
if (i <= max) {
int j = i + 1;
int end = j + target.length - 1;
for (int k = 1; j < end && source[j] == target[k]; j++, k++);
if (j == end) {
return i ;
}
}
}
return -1;
}
The above is all the content of this article, I hope you can enjoy it.