Longest Palindromic Substring - C++


  • 0
    L

    ' ' ' '
    class Solution {
    public:
    string longestPalindrome(string s) {
    int c=count(s.begin(),s.end(),s[0]);
    if(c==s.length()) return s;
    string rs=s;
    reverse(s.begin(),s.end());
    if(rs==s) return s;
    string maxS;
    for(int i=0;i<s.length();i++)
    {
    int j=0;
    int cri=0;
    string nStr;
    nStr+=s[i];

              for(j=1;j<=s.length()-i-1;j++)
            {
               if(s[i]==s[i+j])
               {
                   cri++;
                   nStr+=s[i];
               }
                else
                {
                    break;
                }
            }
           
            
            for(j=1;j<=i;j++)
            {
               if(s[i-j]==s[i+j+cri])
               {
                   nStr=s[i-j]+nStr+s[i-j];
               }
                else
                {
                    break;
                }
            }
            
            if(maxS.length()<nStr.length())
               {
                   maxS=nStr;
               }
            
             
            
           
            
            
        }
          return maxS;
        
    }
    

    };
    ' ' ' '


  • 0
    L

    @LeavyRoll said in Longest Palindromic Substring - C++:

    return

    1. Consider only one character

    2. Consider a symmetric string

    3, consider the string is 'sooos' and 'soooos', find the same character 'ooo' or 'oooo' in the middle.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.