Lec1-计算字符串的相似度
编程之美3.3节
1 //计算字符串的相似度
2 //参见编程之美3.3节
3 //方法:递归
4 //思路:怎样减小问题的规模
5 #include <iostream>
6 #include <cstring>
7 #include <cstdio>
8
9 using namespace std;
10
11 //int x,y,z; //用全局变量和临时变量的区别在哪里?//问题就出现在这里!!!!!!
12 //如果定义为全局变量,存储在静态存储区,在整个函数范围内可以访问。那么后续的调用中会改变x的值。
13 //x的值不能在最初调用的那一层被作为临时变量保存
14
15 int minVal(int a,int b,int c)
16 {
17 return (a<=b?a:b)<=c?(a<=b?a:b):c;
18 }
19
20 int calculateSimilarity(char* a, int i, int j, char* b, int m, int n)
21 {
22 if (i > j)
23 {
24 if (m <= n)
25 return (n - m +1);
26 else
27 return 0;
28 }
29 if (m>n)
30 {
31 if (i<=j)
32 return (j - i + 1);
33 else
34 return 0;
35 }
36
37 //if (*a(i) == *b(m)) 应该是*(a+i)和*(b+m)
38 if (a[i]==b[m])
39 {
40 return calculateSimilarity(a,i+1,j,b,m+1,n);
41 }
42 else
43 {
44 int x = calculateSimilarity(a,i,j,b,m+1,n)+1 ;
45 int y = calculateSimilarity(a,i+1,j,b,m,n)+1 ;
46 int z = calculateSimilarity(a,i+1,j,b,m+1,n)+1;
47 return minVal(x,y,z);
48 }
49 }
50
51 int main()
52 {
53 char a[100];
54 char b[100];
55 int change=0;
56 while (1)
57 {
58 cout<<"Please input the first string:"<<endl;
59 cin>>a;
60 cout<<"Please input the second string:"<<endl;
61 cin>>b;
62 change = calculateSimilarity(a,0,strlen(a)-1,b,0,strlen(b)-1);
63 cout<<"The change needed is "<<change<<endl<<endl;
64 }
65 }
2 //参见编程之美3.3节
3 //方法:递归
4 //思路:怎样减小问题的规模
5 #include <iostream>
6 #include <cstring>
7 #include <cstdio>
8
9 using namespace std;
10
11 //int x,y,z; //用全局变量和临时变量的区别在哪里?//问题就出现在这里!!!!!!
12 //如果定义为全局变量,存储在静态存储区,在整个函数范围内可以访问。那么后续的调用中会改变x的值。
13 //x的值不能在最初调用的那一层被作为临时变量保存
14
15 int minVal(int a,int b,int c)
16 {
17 return (a<=b?a:b)<=c?(a<=b?a:b):c;
18 }
19
20 int calculateSimilarity(char* a, int i, int j, char* b, int m, int n)
21 {
22 if (i > j)
23 {
24 if (m <= n)
25 return (n - m +1);
26 else
27 return 0;
28 }
29 if (m>n)
30 {
31 if (i<=j)
32 return (j - i + 1);
33 else
34 return 0;
35 }
36
37 //if (*a(i) == *b(m)) 应该是*(a+i)和*(b+m)
38 if (a[i]==b[m])
39 {
40 return calculateSimilarity(a,i+1,j,b,m+1,n);
41 }
42 else
43 {
44 int x = calculateSimilarity(a,i,j,b,m+1,n)+1 ;
45 int y = calculateSimilarity(a,i+1,j,b,m,n)+1 ;
46 int z = calculateSimilarity(a,i+1,j,b,m+1,n)+1;
47 return minVal(x,y,z);
48 }
49 }
50
51 int main()
52 {
53 char a[100];
54 char b[100];
55 int change=0;
56 while (1)
57 {
58 cout<<"Please input the first string:"<<endl;
59 cin>>a;
60 cout<<"Please input the second string:"<<endl;
61 cin>>b;
62 change = calculateSimilarity(a,0,strlen(a)-1,b,0,strlen(b)-1);
63 cout<<"The change needed is "<<change<<endl<<endl;
64 }
65 }
你问我生命中还有什么可追寻?