标签:
区别于最长公共字串,下面是最长公共字串的算法,利用DP(动态规划):
void LCS_dp(char * X, int xlen, char * Y, int ylen) { maxlen = maxindex = 0; for(int i = 0; i < xlen; ++i) { for(int j = 0; j < ylen; ++j) { if(X[i] == Y[j]) { if(i && j) { dp[i][j] = dp[i-1][j-1] + 1; } if(i == 0 || j == 0) { dp[i][j] = 1; } if(dp[i][j] > maxlen) { maxlen = dp[i][j]; maxindex = i + 1 - maxlen; } } } } outputLCS(X); }
最长公共字串是可以转化为求最长重复字串的,利用后缀数组的方式:
#include <iostream> using namespace std; #define MAXCHAR 5000 //最长处理5000个字符 char c[MAXCHAR], *a[MAXCHAR]; int comlen( char *p, char *q ) { int i = 0; while( *p && (*p++ == *q++) ) ++i; return i; } int pstrcmp( const void *p1, const void *p2 ) { return strcmp( *(char* const *)p1, *(char* const*)p2 ); } int main(void) { char ch; int n=0; int i, temp; int maxlen=0, maxi=0; printf("Please input your string:\n"); n = 0; while( (ch=getchar())!=‘\n‘ ) { a[n] = &c[n]; c[n++] = ch; } c[n]=‘\0‘; // 将数组c中的最后一个元素设为空字符,以终止所有字符串 qsort( a, n, sizeof(char*), pstrcmp ); for(i = 0 ; i < n-1 ; ++i ) { temp=comlen( a[i], a[i+1] ); if( temp>maxlen ) { maxlen=temp; maxi=i; } } printf("%.*s\n",maxlen, a[maxi]); return 0; }
利用DP算法求最长回文串:
string longestPalindromeDP(string s) { int n = s.length(); int longestBegin = 0; int maxLen = 1; bool table[1000][1000] = {false}; for (int i = 0; i < n; i++) { table[i][i] = true; //前期的初始化 } for (int i = 0; i < n-1; i++) { if (s[i] == s[i+1]) { table[i][i+1] = true; //前期的初始化,针对length为2的回文 longestBegin = i; maxLen = 2; } } for (int len = 3; len <= n; len++) //针对length大于等于3的回文 { for (int i = 0; i < n-len+1; i++) { int j = i+len-1; if (s[i] == s[j] && table[i+1][j-1]) { table[i][j] = true; longestBegin = i; maxLen = len; } } } return s.substr(longestBegin, maxLen); }
标签:
原文地址:http://www.cnblogs.com/xiangcool/p/4454061.html