本篇随笔主要把平时练习的各种算法的小段代码汇集于此,以备日后查看
1.Hanoi递归求解
#include "stdio.h" #include "conio.h" int cout; void move(int h,char c,char f) { printf("%d:%c--->%c\n",h,c,f); cout++; } void hanoi(int n,char x,char y,char z) { if(n==1) move(1,x,z); else { hanoi(n-1,x,z,y); move(n,x,z); hanoi(n-1,y,x,z); } } int main() { int m; loop: cout=0; printf("Input the number of disks:"); scanf("%d",&m); printf("The steps to moving %3d disks:\n",m); hanoi(m,'A','B','C'); printf("the cout is : %d\n",cout); char t; while(1) { printf("是否继续(y/n):"); if((t=getche(),printf("\n\n"),t)=='y') goto loop; if(t=='n') break; } }
2.百度笔试题-最长回文子串
/* 长度为N(N很大)的字符串,求这个字符串里的最长回文子串。 */ #include <stdio.h> #include <stdlib.h> #include <string.h> //第一类“12321”:中间是一个单独的字符 int FindLongPaliSubstr_Odd(const char A[], int * indexMid) { int i = 0, cnt = 0;//cnt表示前后移动位数 int MyMax = 0; int lenOfA = strlen(A); *indexMid = 0; for(i = 1; i <= lenOfA - 2; i++) { cnt = 0; while(i - cnt >= 0 && i + cnt <= lenOfA - 1 && A[i - cnt] == A[i + cnt]) { cnt++; } cnt--; //找到较大长度的回文字符串,保存中心字符的位置 if(MyMax < 2 * cnt + 1) { MyMax = 2 * cnt + 1; *indexMid = i; } } return MyMax; } //第二类“12321”:中间是两个相同的字符。 int FindLongPaliSubstr_Even(const char A[],int * First) { int i = 0, cnt = 0;//cnt表示前后移动位数 int MyMax = 0; int lenOfA = strlen(A); *First = 0;//中间两个相同字符的第一个字符位置 for(i = 0; i <= lenOfA - 2; i++) { if(A[i] == A[i + 1]) { cnt = 1; while(i - cnt >= 0 && (i + 1 + cnt) <= lenOfA - 1 && A[i - cnt] == A[i + 1 + cnt]) { cnt++; } cnt--; //找到较大长度的回文字符串,保存中心第一个字符的位置 if(MyMax < 2 * cnt + 2) { MyMax = 2 * cnt + 2; *First = i; } } } return MyMax; } int main(void) { char A[] = "adfadfbadfdg12ddsf12344321fagage"; int indexMid = 0; int First = 0; int i = 0; //两种类别的最长回文子串的长度 int MaxOdd = FindLongPaliSubstr_Odd(A, &indexMid); int MaxEven = FindLongPaliSubstr_Even(A, &First); printf("indexMid = %d\n", indexMid); printf("First = %d\n", First); //哪类比较大,输出哪一类的回文子串 if( MaxOdd > MaxEven) { for(i = indexMid - (MaxOdd - 1) / 2; i <= indexMid + (MaxOdd - 1) / 2; i++) { putchar(A[i]); } } else { for(i = First - (MaxEven - 2) / 2; i <= First + 1 + (MaxEven - 2) / 2; i++) { putchar(A[i]); } } return 0; }
3.查找相同字符串
#include <iostream> using namespace std; int same(int num) { int cs=num; int sz[20]; int m=0; while(cs!=0) { sz[m]=cs%10; cs=cs/10; m++; } for(int i=0;i<m-3;i++) for(int j=i+2;j<m-1;j++) { if((sz[i]==sz[j])&&(sz[i+1]==sz[j+1])) return 1; } return 0; } int main() { int a,b; cout<<"请输入一串数字"<<endl<<"a="; cin>>a; b=same(a); cout<<(b?"有相同数字串":"没有相同数字串")<<endl; return 0; }