您的位置:首页 > 其它

2013-11-03 实验之最大公共子串(思维逻辑题)

2013-11-03 14:35 429 查看
题目:求字符串的最大公共子串(两个为例)

思路:将长度最小的子串,依次以其长度大小递减,取相应子串,判断该子串是否在另一个串中。

程序实现:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int get_length_of_character(char *s)
{
int count = 0;
while(*s++ != '\0'){
count++;
}
return count;
}

int get_sub_character_of_character(char *s, int k, char *stemp)
{
int i;
int j;
int length = get_length_of_character(s);
char *temp = (char *)malloc(sizeof(char) * (k+1));
int count = 0;
for(i = 0;i < length; i++){
for(j = 0;j < k; j++){
if(j+i < length){
temp[j] = s[j+i];
}else {
break;
}
}
if(j == k){
temp[k] = '\0';
//printf("sub Character %s \n", temp);
if(strstr(stemp, temp)){
printf("The Sub Character is: %s \n", temp);
free(temp);
return 1;
}
}else{
break;
}
}
free(temp);
return 0;
}

int main(void)
{
int maxlength = 256;
char *s1 = (char *)malloc(sizeof(char) * maxlength);
char *s2 = (char *)malloc(sizeof(char) * maxlength);
printf("Please input two character as follows:\n");
scanf("%s", s1);
scanf("%s", s2);
char *s = s1;
char *stemp = s2;

int length1 = get_length_of_character(s1);
int length = length1;
int length2 = get_length_of_character(s2);
//printf("Character %s , length %d\n", s1, length1);
//printf("Character %s , length %d\n", s2, length2);
if(length2 < length1){
s = s2;
length = length2;
stemp = s1;
}
int i;
for(i = length; i >=1; i--){
if(get_sub_character_of_character(s, i, stemp)){
return 0;
}
}
printf("no sub character\n");
return 1;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: