5. Longest Palindromic Substring

来源:互联网 发布:淘宝商城帐篷 编辑:程序博客网 时间:2024/06/09 15:04

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.


class Solution {
public:
    string longestPalindrome(string s) {
         int len = s.length(), max = 1, s_start = 0, s_end = 0;
          bool flag[len][len];
          for (int i = 0; i < len; i++)
              for (int j = 0; j < len; j++)
                  if (i >= j)
                     flag[i][j] = true;
                 else flag[i][j] = false;
         for (int j = 1; j < len; j++)
             for (int i = 0; i < j; i++)
            {
                 if (s[i] == s[j])
                 {
                     flag[i][j] = flag[i+1][j-1];
                     if (flag[i][j] == true && j - i + 1 > max)
                     {
                         max = j - i + 1;
                         s_start = i;
                         s_end = j;
                     }
                 }
                 else flag[i][j] = false;
             }
         return s.substr(s_start, max);
    }
};

0 0
原创粉丝点击