【ATT】Longest Palindromic Substring

O(n)的解法。详情见:http://www.felix021.com/blog/read.php?2040

    string longestPalindrome(string s) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(s.empty())
            return "";
        int mx,i,id;
        //construct p.Transform S into T.For example, S = "abba", T = "^#a#b#b#a#$".
        string str(2*s.size()+3,'$');
        vector<int> p(2*s.size()+2);
        str[0] = '^';
        str[1] = '#';
        int cnt = 2;
        for(i=0;i<s.size();i++)
        {
            str[cnt++] = s[i];
            str[cnt++] = '#';
        }
        
        mx = 0;
        for(i=1;i<cnt;i++)
        {
            if(mx<=i)
                p[i] = 1;
            else
                p[i] = min(mx-i,p[2*id-i]);
            
            while(str[i-p[i]]==str[i+p[i]])
                p[i]++;
            
            if(i+p[i]>mx)
            {
                mx = i+p[i];
                id = i;
            }
        }
        int max_len = 0;
        int cur_idx = 0;
        for(i=1;i<cnt;i++)
        {
			if(p[i]-1>max_len)
			{
				max_len = p[i] -1;
				cur_idx = i;
			}
        }
        return s.substr((cur_idx - 1 - max_len)/2, max_len);
        
    }

  

posted @ 2013-10-04 21:36  summer_zhou  阅读(142)  评论(0编辑  收藏  举报