Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
思路1:中心扩展法,枚举中心的文职,再在该位置上扩展,记录并更新得到的最长回文串的长度。注意需要区分回文子串是奇数长度还是偶数长度。
-
class Solution { public: string longestPalindrome(string s) { int len = s.length(); int max_l = 0;//最长回文子串长度 int max_s = 0;//最长回文子串开头的位置 int cur_len; int cur_s; for (int i = 0; i < len; i++) {//字符串的长度是奇数 for (int j = 0; i + j<len&&i - j>-1; j++) { if (s[i + j] != s[i - j]) { break; } cur_len = j * 2 + 1; cur_s = i - j; } if (cur_len > max_l) { max_s = cur_s; max_l = cur_len; } for (int j = 0; i - j > -1 && i + j + 1 < len; j++) {//字符串为偶数长度 if (s[i + j + 1] != s[i - j]) { break; } cur_len = 2 * j + 2; cur_s = i - j; } if (cur_len > max_l) { max_s = cur_s; max_l = cur_len; } } return s.substr(max_s, max_l); } };