求两个字符串最大的公共字串的长度
2015-09-10 17:13
399 查看
求两个字符串最大的公共字串的长度
1、暴力解法
2、动态规划(待完善)
1、暴力解法
#include <stdio.h> #include <string.h> #include <stdlib.h> /*大写转化成小写*/ void large_to_little(char* strSrc) { if(!strSrc) return; while ( *strSrc != '\0') { if ( *strSrc >= 'A' && *strSrc <= 'Z') { *strSrc = *strSrc +'a'-'A'; } strSrc ++; } } /*获取当前字符串的长度*/ int getCurCommonStrLength(char* pFirstStr,char* pSecondStr) { int nLength = 0; if(!pFirstStr||!pSecondStr) return 0; while ((*pFirstStr == *pSecondStr)&&(*pFirstStr!='\0'||*pSecondStr!='\0')) { nLength++; pFirstStr ++; pSecondStr++; } return nLength; } /*获取公共字符串的长度*/ int getCommonStrLength(char * pFirstStr, char * pSecondStr) { if(!pFirstStr||!pSecondStr) return 0; if(pFirstStr==""||pSecondStr=="") return 0; /*1.大小写会改变原字符串,保留原字符串*/ int pFirstStrLen = strlen(pFirstStr); int pSecondStrLen = strlen(pSecondStr); /*字符串结束标志位*/ char *pFirstStrTemp = (char *)malloc(pFirstStrLen*sizeof(char)+1); char *pSecondStrTemp = (char *)malloc(pSecondStrLen*sizeof(char)+1); strcpy(pFirstStrTemp,pFirstStr); strcpy(pSecondStrTemp,pSecondStr); /*转换成小写*/ large_to_little(pFirstStrTemp); large_to_little(pSecondStrTemp); /*2.获取公共字符串长度*/ int CommonStrLengthMax = 0; char* strFirst = pFirstStrTemp; char* strSecond = pSecondStrTemp; //printf("[%d] strFirst %s\n",__LINE__,strFirst); //printf("[%d] strFirst %s\n",__LINE__,strSecond); while ( *strFirst != '\0') { while ( *strSecond != '\0') { if ( *strFirst == *strSecond) { int nTempCommon = getCurCommonStrLength(strFirst,strSecond); if ( nTempCommon > CommonStrLengthMax) { CommonStrLengthMax = nTempCommon; //printf("[%d] CommonStrLengthMax %d\n",__LINE__,CommonStrLengthMax); } } strSecond++; } strSecond = pSecondStrTemp; /*重新赋值*/ //printf("[%d] strFirst %s\n",__LINE__,strSecond); strFirst++; } free(pFirstStrTemp); free(pSecondStrTemp); return CommonStrLengthMax; } int main() { #if 0 char* str1 = "asdfas"; char* str2= "werasdfaswer"; #endif #if 0 char* str1 = "123456"; char* str2= "123564123456"; #endif #if 0 char str1[1024]; char str2[1024]; gets(str1); gets(str2); #endif /*1.输入字符串之间要有空格*/ #if 1 char str1[1024]; char str2[1024]; scanf("%s %s",str1,str2); #endif //printf("%s\n",str1); int CommonStrLengthMax = getCommonStrLength(str1,str2); printf("%d\n",CommonStrLengthMax); #if 0 getchar(); getchar(); #endif return 0; }
2、动态规划(待完善)
相关文章推荐
- HTML5中40个最重要的技术点
- systemtap跟踪C
- css3 animation 参数详解
- 使用python实现自动“扫描检测硬件改动”功能
- Linux学习:vim程序编辑器
- memcache/redis
- Android adb无法启动
- 使用LinuxLive USB Creator创建便携式Linux系统
- Maven常用插件
- 关于const常量、const指针以及const引用
- 【hdoj 1164】Eddy's research I
- ipa文件通过url下载
- 委托者模式和策略模式的区别
- Maven常用插件
- MojoDatabase 源码学习之对象映射
- Web Service 简介
- MojoDatabase 源码学习之对象映射
- Win8每次开机都要两次怎么办?故障分析以及解决办法
- Groovy调用示例
- mongo表id自动生成