1. 程式人生 > >leetcode 5:最長迴文子串

leetcode 5:最長迴文子串

std::string longestPalindrome(std::string s){
    if(s.size()==0)return "";
    if(s.size()==1)return s;
    int max=0;
    int start=0;
    for(int i=0;i<s.size()-1;i++)
    {
        int s1=i;
        int t1=s.size()-1;
        int t=s.size()-1;
        while(s1<t)
        {
            if(s[s1]!=s[t]){
                s1=i;
                t1--;
                t=t1;
            }
            else if(s[s1]==s[t]){
                s1++;
                t--;
            }
        }
        if(t1-i+1>max)
        {
            start=i;
            max=t1-i+1;
        }
    }
    return s.substr(start,max);
}