查找两个字符串中的最大公共子串
2017-03-26 22:14
471 查看
/********************************************************* - Copyright (C): 2016 - File name : commonstring.c - Author : - Zxn - - Date : 2016年08月28日 星期日 16时31分21秒 - Description : * *******************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> char *commonstring(char *str1, char *str2) { int i; int j; char *shortstr; char *longstr; char *substr; //参数检测 if (NULL == str1 || NULL == str2) { return NULL; } //确定长短字符串 if (strlen(str1) <= strlen(str2)) { shortstr = str1; longstr = str2; } else { shortstr = str2; longstr = str1; } //如果断字符串直接就是长字符串的子串则直接返回 if (strstr(longstr, shortstr) != NULL) { return shortstr; } //创建一个临时空间 substr = (char *)malloc(sizeof(char)*(strlen(shortstr)+1)); //这里利用两层循环对短字符串不断的缩短,然后在长字符串中查找,如果 //找到则返回 //算法示例: //longstr = "hgfasdxcv" //shortstr = "svasdg" //外层for每次让短字符串从后面开始向前减少, //比如svasdg-->svasd-->svas>...直到没有 //而内层for每次让短字符串从前面开始向后减少 //比如当i = 5时,shortstr = "svasd"; //j = 0, substr = svasd; //j = 1, substr = vasd; //j = 2, substr = asd //....如此往复直到找到最终答案 for (i = strlen(shortstr) - 1; i > 0; i--) { for (j = 0; j <= strlen(shortstr) - i;j++) { memcpy(substr, &shortstr[j], i); substr[i] = '\0'; if (strstr(longstr, substr) != NULL) { return substr; } } } return NULL; } int main() { char *str1 = (char *)malloc(256); char *str2 = (char *)malloc(256); char *common = NULL; gets(str1); gets(str2); common = commonstring(str2, str1); printf("the longest common string is %s\n", common); return 0; }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
程序运行结果
相关文章推荐
- 编程实现查找两个字符串的最大公共子串 示例:"aocdfe"和"pmcdfa"最大公共子串为"cfd"
- c语言:查找两个字符串的最大公共子串
- [C/C++笔面试]编程查找两个字符串中的最大公共子串
- 编程查找两个字符串最大公共子串
- java实现字符串匹配问题之求两个字符串的最大公共子串
- 华为(8)查找两个字符串a,b中的最长公共子串
- 求两个字符串的最大公共子串
- 两个或N个字符串最大公共子串算法
- 查找两个字符串的最长公共子串(附源码)_AX
- 华为练习--查找两个字符串a,b中的最长公共子串
- 两个字符串的最大公共子串
- 找出两个字符串的最大公共子串
- 求两个字符串的公共最大子字符串,如asdfsdkgf,kllsdkabc的最大子串为sdk
- 求两个字符串的最大公共子串 ,不区分大小写
- 查找两个串的最大公共子串
- 动态规划算法求两个字符串的最大公共子串
- 两个或N个字符串最大公共子串算法
- 两个或N个字符串最大公共子串算法
- 求两个字符串的最大公共子串
- 查找两个字符串的最大相同子串