https://leetcode.com/problems/longest-palindromic-substring/
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb"
class Solution { public: string longestPalindrome(string s) { } };
class Solution { public: string longestPalindrome(string s) { if (s.size() <=1) return s; int longestSiz = 1; int longestBeg = 0; int longestEnd = 0; for (int i = 0; i < s.size() -1; i ++){ # consider the palindromic sub string using s[i] as the center int j = 1; while ((i -j) >=0 && (i + j) < s.size()){ if (s[i -j] == s[i +j]) j ++; else break; } int localLongestSiz = 1 + 2 * (j -1); int localLongestBeg = i - j +1; int localLongestEnd = i + j -1; if (localLongestSiz > longestSiz){ longestSiz = localLongestSiz; longestBeg = localLongestBeg; longestEnd = localLongestEnd; } # consider the palindromic sub string has even characters and s[i] is the on the left half ner the middle if (s[i] == s[i+1]){ j = 1; while ( (i-j) >= 0 && (j+1 + j) < s.size()){ if (s[i -j] == s[i +1 + j]) j ++; else break; } localLongestSiz = 2 * j; localLongestBeg = i - j + 1; localLongestEnd = i + 1 + j -1; if (localLongestSiz > longestSiz){ longestSiz = localLongestSiz; longestBeg = localLongestBeg; longestEnd = localLongestEnd; } } } return s.substr(longestBeg, longestSiz); } };