2 years ago
#338099
233
How to remove the pattern string until there is no pattern string in the text?
Problem Descripition
You are given 2 strings,
textandpattern, you should do the following operations
If
patternis not intext, goto 4delete the first occurrence of
patternintextgoto 1
print current
textend
I try to solve this problem using KMP Algorithm. I find the delete operation will cost much time, so I use another textNext array to store the next element's index of text string to skip the pattern string in text(avoiding really deleting it from text). For example, text is ukpkmkk, and the pattern is pk. After executing the operations, textNext should be {1,4,3,4,5,6,7}(textNext is initialized to i+1 for element). I use the code below to traverse the string after those operations.
for (int i = 0; i < text.length(); i = textNext[i]) {...}
My problem is that I can't get the correct result using my algorithm. Here is my code.
public static void main(String[] args) {
String text = in.next();
String pattern = in.next();
int[] textNext = new int[text.length()];
for (int i = beginIndex; i < textNext.length; i++) {
textNext[i] = i + 1;
}
while (kmp(text, pattern, textNext) != -1) {}
for (int i = beginIndex; i < text.length(); i = textNext[i]) {
out.print(text.charAt(i));
}
out.println("");
out.close();
}
public static int kmp(String text, String pattern, int[] textNext) {
int[] patternNext = buildNext(pattern);
int head = 0;
for (int i = beginIndex, j = 0; i < text.length(); i = textNext[i]) {
while (j > 0 && text.charAt(i) != pattern.charAt(j)) {
j = patternNext[j - 1];
}
if (text.charAt(i) == pattern.charAt(j)) {
if (j == 0) {
head = i;
}
j++;
}
if (j == pattern.length()) {
if (head == 0) {
beginIndex = i + 1;
} else {
textNext[head - 1] = i + 1;
}
return head;
}
}
return -1;
}
public static int[] buildNext(String pattern) {
int[] next = new int[pattern.length()];
next[0] = 0;
for (int i = 1, j = 0; i < next.length; i++) {
while (j > 0 && pattern.charAt(i) != pattern.charAt(j)) {
j = next[j - 1];
}
if (pattern.charAt(i) == pattern.charAt(j)) {
j++;
}
next[i] = j;
}
return next;
}
Please point out where my algorithm's problem is or just offer other way to solve this problem.
java
string
string-matching
0 Answers
Your Answer