码迷,mamicode.com
首页 > 其他好文 > 详细

求给定字符串中最长回文子串

时间:2017-09-28 11:34:44      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:tor   code   turn   style   r++   splay   first   sub   long   

 

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 }

求给定字符串中最长回文子串

标签:tor   code   turn   style   r++   splay   first   sub   long   

原文地址:http://www.cnblogs.com/tuhooo/p/7605697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!