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.
思路:遍历字符串S,从每个下标开始向两侧扩展找到当前最大的回文并保存起始位置和长度,最后返回最长的
class Solution { public: int startIndex = 0; int maxLength = 0; string longestPalindrome(string s) { int length = s.size(); if(length < 2) { return s; } for(int i=0;i<length-1;i++) { getLongestPalindromicString(s,i,i); getLongestPalindromicString(s,i,i+1); } return s.substr(startIndex,maxLength); } void getLongestPalindromicString(string s,int left,int right) { while(left >= 0 && right < s.size() && s[left] == s[right]) { left--; right++; } int length = right - left - 1; if(maxLength < length) { maxLength = length; startIndex = left + 1; } } };