首页 > 代码库 > 给一个字符串,找到其最长的回文字串

给一个字符串,找到其最长的回文字串

直接上代码:

 1 string expendCentral(string, int); 2  3 string longestPalindrome(string s) 4 { 5     int len = s.size(); 6     if (len == 0) 7         return ""; 8     string maxStr = s.substr(0, 1); 9     for (int i = 0; i < len - 1; i++) {10         string expendStr = expendCentral(s, i);11         if (expendStr.size() > maxStr.size())12             maxStr = expendStr;13     }14     return maxStr;15 }16 17 string expendCentral(string s, int d)18 {19     int l1 = d;20     int r1 = d;21     while (l1 - 1 >= 0 && r1 + 1 < s.size()) {22         if (s[l1-1] == s[r1+1]) {23             l1--;24             r1++;25         }26     }27     int len1 = r1 - l1 + 1;28     int len2 = 0;29     int l2 = d;30     int r2 = d + 1;31     if (s[d] == s[d+1]) {32         while (l2 - 1 >= 0 && r2 + 1 < s.size()) {33             if (s[l2-1] == s[r2+1]) {34                 l2--;35                 r2++;36             }37         }38         len2 = r2 - l2 + 1;39     }40     if (len1 > len2)41         return s.substr(l1, r1-l1+1);42     else43         return s.substr(l2, r2-l2+1);44 }        

 

给一个字符串,找到其最长的回文字串