[leetcode] 5. Longest Palindromic Substring

 

I. Lessons learned:

  I.1 string STL::string::substr(size_t start_index, size_t sub_str_len);

 

/********************************************/

1. Question:

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

2. Solution:

所谓的回文子串,就是一个对称的字符串,要么奇数对称,要么偶数对称。

遍历字符串,求出以s[i]为中心时最大的回文子串。以s[1]='a'为中心的子串有下面三种情况需要考虑(粗体表示对称中心):

  a. 奇数对称:“baabc"

  b. 偶数对称: "baabc"

  c. 偶数对称: "baabc"

但是,对第三种情况,以s[2]='a'为中心时又会重复搜索一遍,因此只需要考虑a、b两种情况。

#include <string>
#include <iostream>
using namespace std;

class Solution {
public:
    string longestPalindrome(string s)
    {
        int outl = 0;
        string outs = "";
        for(int i=0; i<s.size(); i++)
        {
            int templ1 = 0;
            while((i - templ1 >= 0) && (i + templ1 < s.size()) && (s[i - templ1] == s[i + templ1]))
            {
                templ1++;
            }
            if(outl < templ1 * 2 - 1)
            {
                outl = templ1 * 2 - 1;
                outs = s.substr(i - templ1 + 1, outl);
            }

            int templ2 = 0;
            while((i - templ2 >= 0) && (i + 1 + templ2 < s.size()) && (s[i - templ2] == s[i + 1 + templ2]))
            {
                templ2++;
            }
            if(outl < templ2 * 2)
            {
                outl = templ2 * 2;
                outs = s.substr(i - templ2 + 1, outl);
            }
        }
        return outs;
    }
};

int main()
{
    string s1 = "123bab93";
    string s2 = "a";
    string s3 = "";
    string s4 = "aa";
    
    Solution s;
    cout << s.longestPalindrome(s1) << endl;

    system("pause");
    return 0;
}

你可能感兴趣的:(substring)