classSolution{public:stringlongestPalindrome(strings){if(s.empty())return"";// [start, end] indices of the longest palindrome in spair<int,int>indices{0,0};for(inti=0;i<s.length();++i){constauto[l1,r1]=extend(s,i,i);if(r1-l1>indices.second-indices.first)indices={l1,r1};if(i+1<s.length()&&s[i]==s[i+1]){constauto[l2,r2]=extend(s,i,i+1);if(r2-l2>indices.second-indices.first)indices={l2,r2};}}returns.substr(indices.first,indices.second-indices.first+1);}private:// Returns [start, end] indices of the longest palindrome extended from// s[i..j]pair<int,int>extend(conststring&s,inti,intj){for(;i>=0&&j<s.length();--i,++j)if(s[i]!=s[j])break;return{i+1,j-1};}};
classSolution{publicStringlongestPalindrome(Strings){if(s.isEmpty())return"";// [start, end] indices of the longest palindrome in sint[]indices={0,0};for(inti=0;i<s.length();++i){int[]indices1=extend(s,i,i);if(indices1[1]-indices1[0]>indices[1]-indices[0])indices=indices1;if(i+1<s.length()&&s.charAt(i)==s.charAt(i+1)){int[]indices2=extend(s,i,i+1);if(indices2[1]-indices2[0]>indices[1]-indices[0])indices=indices2;}}returns.substring(indices[0],indices[1]+1);}// Returns [start, end] indices of the longest palindrome extended from s[i..j]privateint[]extend(finalStrings,inti,intj){for(;i>=0&&j<s.length();--i,++j)if(s.charAt(i)!=s.charAt(j))break;returnnewint[]{i+1,j-1};}}
classSolution:deflongestPalindrome(self,s:str)->str:ifnots:return''indices=[0,0]# Returns [start, end] indices of the longest palindrome extended from s[i..j]defextend(s:str,i:int,j:int)->Tuple[int,int]:whilei>=0andj<len(s):ifs[i]!=s[j]:breaki-=1j+=1returni+1,j-1foriinrange(len(s)):l1,r1=extend(s,i,i)ifr1-l1>indices[1]-indices[0]:indices=l1,r1ifi+1<len(s)ands[i]==s[i+1]:l2,r2=extend(s,i,i+1)ifr2-l2>indices[1]-indices[0]:indices=l2,r2returns[indices[0]:indices[1]+1]