求给定字符串中最长回文子串
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了求给定字符串中最长回文子串相关的知识,希望对你有一定的参考价值。
5. Longest Palindromic Substring
这个是在本机测试,然后一次点亮的,嘻嘻
1 char* longestPalindrome(char* s) { 2 char *p = s; /* first char */ 3 char *left, *right; /* store the pointer of longest palindrome string */ 4 int max = 0; /* store max length */ 5 while(*p != ‘\\0‘) { 6 char *l = p; 7 char *r = p; 8 int count = 0; 9 while(1) { 10 if(*l == *r) { 11 if(p==l) 12 count += 1; 13 else 14 count += 2; 15 if(l == s || *(r+1) == ‘\\0‘) { 16 if(max < count) { 17 max = count; 18 left = l; 19 right = r; 20 } 21 break; 22 } 23 l--; 24 r++; 25 } else { 26 if(max < count) { 27 max = count; 28 left = ++l; 29 right = --r; 30 } 31 break; 32 } 33 } 34 p++; 35 } 36 37 p = s; 38 while( *(p+1) != ‘\\0‘) { 39 40 int count = 0; 41 if(*p == *(p+1)) { 42 char *l = p; 43 char *r = p+1; 44 count = 2; 45 while(1) { 46 47 if(*l == *r) { 48 if(l != p) 49 count += 2; 50 51 if(l==s || *(r+1) == ‘\\0‘) { 52 if(max < count) { 53 max = count; 54 left = l; 55 right = r; 56 } 57 break; 58 } 59 l--; 60 r++; 61 } else { 62 if(max < count) { 63 max = count; 64 left = ++l; 65 right = --r; 66 } 67 break; 68 } 69 } 70 } 71 p++; 72 } 73 74 for(p=left; p<=right; p++) 75 printf("%c", *p); 76 *(right+1) = ‘\\0‘; 77 return left; 78 }
以上是关于求给定字符串中最长回文子串的主要内容,如果未能解决你的问题,请参考以下文章