實現KMP算法查找字符串。算法
///簡單查找
func simpleSearch(_ src: String, _ mode: String, _ start: Int) -> Int {
var i = start;
while i < src.count {
var j = 0;
while j < mode.count {
if(i + j >= src.count || src[i + j] != mode[j]){
break;
}
j += 1;
}
if j == mode.count{
return i;
}
i += 1;
}
return -1;
}
///kmp字符串查找
func kmpSearch(_ src: String, _ mode: String, _ start: Int) -> Int {
//計算next
var next: [Int] = [0, 0];
//自身匹配,i表示主下標,j表示匹配下標
var i = 2, j = 0;
while i < mode.count {
if(mode[i - 1] == mode[j]){
next[i] = j + 1;
i += 1;
j += 1;
}else{
if(j == 0){
i += 1;
}
//已經匹配的部分有可能會有首尾相同的狀況
j = next[j];
}
}
//算法同自身匹配
i = start;
j = 0;
while i < src.count {
if(src[i] == mode[j]){
i += 1;
j += 1;
if(j == mode.count){
return i - mode.count;
}
}else{
if(j == 0){
i += 1;
}
j = next[j];
}
}
return -1;
}
複製代碼
function simpleSearch(src, mode, start){
for(let i = start; i < src.length; i++){
let miss = false;
for(let j = 0; j < mode.length; j++){
if(i + j >= src.length){
miss = true;
break;
}else if(src.charAt(i + j) != mode.charAt(j)){
miss = true;
break;
}
}
if(!miss){
return i;
}
}
return -1;
}
function kmpSearch(src, mode, start){
let next = [0, 0];
let i = 2;
let j = 0;
while (i < mode.length) {
if(mode.charAt(i - 1) == mode.charAt(j)){
j++;
i++;
next[i-1] = j;
}else{
if(j == 0){
i++;
}
j = next[j];
}
}
i = start;
j = 0;
let found = false;
while (i <= src.length) {
if(src.charAt(i) == mode.charAt(j)){
i++;
j++;
if(j == mode.length){
found = true;
break;
}
}else{
if(j == 0){
i++;
}
j = next[j];
}
}
if(found){
return i - mode.length;
}else{
return -1;
}
}
複製代碼