5. Longest Palindromic Substring

  • start, end index의 쑰합을 λͺ¨λ‘ μ‹œλ„ν•˜μ—¬ palindrome을 찾아보렀고 ν–ˆμœΌλ‚˜ μ‹€νŒ¨ν•¨.
  • κ°œλ³„ indexλ₯Ό κΈ°μ€€μœΌλ‘œ μ–‘ μ˜†μœΌλ‘œ κΈ€μžλ₯Ό ν™•μž₯ν•˜λ©΄μ„œ palindrome이 ꡬ성가λŠ₯ν•œμ§€ μ•Œμ•„λ³Έλ‹€.
    • 단, ν™•μž₯ν•  λ•Œ 길이가 ν™€μˆ˜, 짝수인 경우λ₯Ό λͺ¨λ‘ κ³ λ €ν•΄μ•Ό ν•œλ‹€.
    • ν™€μˆ˜μΈ κ²½μš°λŠ” ν˜„μž¬ indexλ₯Ό κΈ°μ€€μœΌλ‘œ μ–‘μ˜†μœΌλ‘œ 1κ°œμ”© ν™•μž₯ν•˜λ©° 같은지 λΉ„κ΅ν•œλ‹€.
    • 짝수인 κ²½μš°λŠ” ν˜„μž¬ index와 λ°”λ‘œ κ·Έ λ‹€μŒ indexκ°€ 같은지 λΉ„κ΅ν•˜κ³  κ·Έ λ‹€μŒλΆ€ν„° μ–‘μ˜†μœΌλ‘œ 1κ°œμ”© ν™•μž₯ν•˜λ©° 같은지 λΉ„κ΅ν•œλ‹€.
class Solution { public: pair<int, int> expand(string& s, int start, int end) { while (start >= 0 && end < s.length() && s[start] == s[end]) { --start; ++end; } return {start + 1, end - 1}; } string longestPalindrome(string s) { pair<int, int> result = {0, 0}; for (int i = 0; i < s.length(); ++i) { // odd length auto cur = expand(s, i, i); if (cur.second - cur.first > result.second - result.first) result = cur; // even length if (i == s.length() - 1 || s[i] != s[i + 1]) continue; cur = expand(s, i, i + 1); if (cur.second - cur.first > result.second - result.first) result = cur; } return s.substr( result.first, result.second - result.first + 1); } };