JS實現手風琴特效
阿新 • • 發佈:2020-11-09
說明:給出文字串和模式串,找出模式串在文字串中出現的位置
解法:
1、暴力解法(BF)
int BF(string s, string t, int lens, int lent) { int i = 0, j = 0; while (i < lens && j < lent) { if(s[i] == t[j]) { i++; j++; } else { i = i + j - 1; j = 0; } }if (j == lent) { return i - j; } else return -1; }
2、KMP解法
說明:i不回溯,移動模式串
右移位數 = 失配所在位置 - 失配對應的next[]值
(next[j] = k :j之前的字串有最大長度k的相同字首字尾)
void get_next() { int i = 0, j = -1; next[0] = -1; while (i < lent) { if (j == -1 || t[i] == t[j]) next[++i] = ++j;else j = next[j]; } }
void KMP() { int i = 0, j = 0; while (i < lens) { if (j == -1 || s[i] == t[j]) { i++; j++; } else j = next[j]; if (j == lent) { cout << i - lent + 1; j = next[j]; } } }