题目:https://leetcode.com/problems/longest-palindromic-substring/
思路:
分为两种回文,一种是”aba”的形式,另一种是”aa”的形式,当然了,”a”也算是回文.
我的想法指定一个对称中心,然后往两边搜索,这样能找到最大可能的回文。或许还有一种思路是利用类似栈的容器的,但是怎样判断”abcbaabcba”这种嵌套型的呢?
代码:
class Solution { public: string longestP(string s, int pos, int type) { //Type: 0- 'a', 1-'aa' //Find palindrome at the position 'pos' int len = s.size(); int posFront, posRear, maxLen; if (type == 0) { maxLen = 1; //'a' posFront = pos - 1; posRear = pos + 1; if (posFront < 0) return s; } else { maxLen = 0; posFront = pos - 1; posRear = pos; } while (posRear - posFront + 1 <= len) { if (s[posFront] != s[posRear]) { if (maxLen == 0) return ""; return s.substr(posFront + 1, posRear - posFront - 1); } posFront--; posRear++; maxLen+=2; } return s.substr(posFront + 1, posRear - posFront - 1); } string longestPalindrome(string s) { int strSize = s.size(); string maxStr = s.substr(0,1); for (int i = 1; i<strSize; i++) { string type1str = longestP(s, i, 0); string type2str = longestP(s, i, 1); if (type1str.size() > maxStr.size()) { maxStr = type1str; } if (type2str.size() > maxStr.size()) { maxStr = type2str; } } return maxStr; } };