本文章学习于蓝桥杯算法训练-斐波那契串_天下一般的博客-CSDN博客_蓝桥杯斐波那契串
由于对KMP算法的不够了解与该博主的编译水平过高,我将再次对其进行解释与说明。
- 暴力解法(其实不暴力)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = Long.parseLong(sc.nextLine());
String S = sc.nextLine();
String pre = "0";
StringBuffer next = new StringBuffer("1");
if(S.compareTo("0") == 0){
System.out.println(Fibonacci(0,n));//如果s是0,就直接开始计算个数
}else if (S.compareTo("1") == 0){
System.out.println(Fibonacci(1,n));//如果s是1,就直接开始计算个数
}
for(long i = 0;i<=n;i++){
String temp = next.toString();
next.append(pre);
pre = temp;
if(pre.contains(S)){//简单的类Fibonacci累加,直到出现S。之后的优化算法是contains函数
System.out.println(Fibonacci(i,n));
break;
}
}
}
private static long Fibonacci(long n,long m){
long a=0,b=1;
for(long i=n;i<=m;++i){
long t = b;
b += a;
a = t;
}
return b-1;//b-1不明白是为什么,理解为是之前借来一个
}
}
2.
2.1KMP理论部分
KMP简单来说就是通过提前对待测字符串进行标号,使得在实战寻找时在被寻字符串中的指针不需要移动,言简意赅就是极小的空间复杂度换时间:)
简直就是秦始皇吃花椒,赢麻了
KMP算法及其优化(超详解)_Veritaswhs的博客-CSDN博客_kmp的优化该博主讲的已经很详细了,但是为了具体观看,建议大家前往某蓝色视频网站观看具体详解。主要是关于考研所需的应试技巧,对于实战帮助不大
2.2实战部分
主要是对其中的contains算法进行进一步优化
在博主的学习过程中,在各大视频网站上最多的就是对于KMP算法的应试技巧。
主要是为了应对考研要求,大部分都浅尝辄止
博主的KMP代码部分目前实施尚未成功
伪代码如下:
import java.util.*;
public class Main {
private static String s;
private static int[] nx;
private static boolean KMP(String pre){
char[] t = pre.toCharArray();//需测长度
char[] st = s.toCharArray();
int n = t.length,m = st.length;
nx = new int[n+1];
int j=0,k=-1;
nx[j] = -1;
while(j<n){
if(k == -1||t[j] == t[k]){//基础薄弱同学建议一步一步带入跟着走
j++;k++;
if(j!=n && t[j] == t[k])nx[j]=nx[k];
else nx[j] = k;
}else k = nx[k];//k大部分为-1/0
}
j=0;int i=0;//将KMP的nextval求出之后进行寻找
while (i<m){
if(j == -1 || st[i] == t[j]){
i++;j++;
}else j = nx[j];//核心部分
if (j == n)return true;
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = Long.parseLong(sc.nextLine());
s = sc.nextLine();
String pre = "0";
StringBuffer next = new StringBuffer("1");
if(s.compareTo("0") == 0){
System.out.println(Fibonacci(0,n));
}else if (s.compareTo("1") == 0){
System.out.println(Fibonacci(1,n));
}
for(long i = 0;i<=n;i++){
String temp = next.toString();
next.append(pre);
pre = temp;
if(KMP(pre)){
System.out.println(Fibonacci(i,n));
break;
}
}
}
private static long Fibonacci(long n,long m){
long a=0,b=1;
for(long i=n;i<=m;++i){
long t = b;
b += a;
a = t;
}
return b-1;
}
}
位置 | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
t[ ] | A | B | C | A | B | D | C |
nextval[ ] | -1 | 0 | 0 | -1 | 0 | 2 |
博主在后续学习通透之后,会继续更新。爱你们~