您的位置:首页 > 产品设计 > UI/UE

POJ 1458 Common Subsequence (暴力枚举)

2015-10-10 10:47 417 查看
//暴力枚举,穷举第一个字符串所有的子序列,对每个子序列检查是否也是第二个字符串的子序列,记录找到最长的子序列,会超时
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000

char str1[MAX_LEN];
char str2[MAX_LEN];
char stack[MAX_LEN];
int top;
int lenOfCS;//length of longest commom subsequence
int result;

int compareStr2(){
int indexOfStr2 = 0;
int i;
for (i = 0; i < top; i++){
char cha = stack[i];
while (str2[indexOfStr2] != '\0' && str2[indexOfStr2] != cha)
indexOfStr2++;
if (str2[indexOfStr2] == '\0')
return 0;
}
return 1;
}

void selectSubSequenceOfStr1(int index){

if (str1[index] == '\0'){
if (top <= result)
return;

if (compareStr2() == 1)
result = top;
return;
}
stack[top++] = str1[index];
selectSubSequenceOfStr1(index + 1);
top--;
selectSubSequenceOfStr1(index + 1);
}

int main(){
freopen("input.txt", "r", stdin);

while (scanf("%s%s", str1, str2) != EOF){
top = 0;
result = 0;
selectSubSequenceOfStr1(0);
printf("%d\n", result);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息