求最大公共子串
程序员文章站
2022-07-14 10:14:54
...
#include <stdio.h> #include <stdlib.h> #include <string> using namespace std; struct stringtag { string value; int tag; }; int stringcompare(const void* A,const void* B) { struct stringtag* AA = (struct stringtag*)A; struct stringtag* BB = (struct stringtag*)B; return (*AA).value.compare( (*BB).value); } int cutstring(struct stringtag strarr[],int arrsize,string sourcestr,int tag) { int i = 0; for(; i < arrsize && i < sourcestr.length(); i ++){ strarr[i].tag = tag; strarr[i].value = sourcestr.substr(i); } return i; } int getmatchstr(struct stringtag A,struct stringtag B) { int i = 0; for(; i < A.value.length() && i < B.value.length();i ++) if(A.value.c_str()[i] != B.value.c_str()[i]) break; return i; } int main(int argc,char* argv[]) { string testa = "awerdasadfdfdfqedfjhoqewhjkhadsf"; string testb = "weqwdadfefdzxcverqrjhr"; struct stringtag aArr[100] = {""}; int len = cutstring(aArr,100,testa,0); len = cutstring(aArr+len,100 -len,testb,1) + len; qsort(aArr,len,sizeof(struct stringtag),stringcompare); int matchlen = 0,maxindex = 0; for(int i = 0; i < len -1; i ++ ) { if(aArr[i].tag != aArr[i+1].tag) { int tmplen = getmatchstr(aArr[i],aArr[i+1]); if(tmplen > matchlen) { matchlen = tmplen; maxindex = i; } } } printf("max common substr:%s \n",aArr[maxindex].value.substr(0,matchlen).c_str()); return 0; }
上一篇: 呼叫中心数据分析
下一篇: 从java转向C\c++开发要学会些什么