The idea of KMP pattern matching algorithm : the target string a subscript is i and the pattern string b subscript is j. The comparison starts from the first character. If they are equal, i and j are incremented at the same time. If they are not equal, b[j] = next[ j]. The next array is derived from the pattern string b, which can be roughly understood as that there are multiple prefixes and suffixes before the current subscript of b[j]. Not much to say, code
// An highlighted block(functionspeedOrder(){
let a ="abcadbacabcabcdab";let b ="bcabcd";
console.log(mate(a,b))/**
* 主串与模式串匹配
*/functionmate(objString,mateString){
/**
* 获取next()数组
*/functiongetNext(orderString){
let next =[-1]let k =-1let j =0while(j < orderString.length-1){
if( k ==-1|| orderString[j]== orderString[k]){
j++
k++if(orderString[j]!= orderString[k]){
next[j]= k
}else{
next[j]= next[k]}}else{
k =-1}}return next
}const next =getNext(b);
console.log(next)let i =0;let j =0;while( i < objString.length && j < mateString.length ){
if( j==-1|| objString[i]== mateString[j]){
i++;
j++;}else{
j=next[j];}}if(j==mateString.length){
returntrue}returnfalse}})()
Two random arrays take the sum of the largest three numbers. Idea: Sort the random array first, take the last three digits in ascending order, and add the first three digits in descending order. code show as below
functionzjh(size){
//指定随机数个数let a =[];let b =[];for(let i =0; i < size ; i++){
a.push(parseInt(Math.random()*10));
b.push(parseInt(Math.random()*10));}
console.log(a)
console.log(b)
a.sort();//排序方法,升序
b.sort();
console.log(a)
console.log(b)let person1=add(a[size-1],a[size-2],a[size-3]);let person2=add(b[size-1],b[size-2],b[size-3]);if(person1>=person2){
console.log(person1)}else{
console.log(person2)}/**
* 求和方法
*/functionadd(){
let size=Array.from(arguments);//转换类数组let sum =0;for(let s of size){
sum += s;}return sum;}}zjh(5)