Leetcode 之Longest Palindromic Substring(30)

很经典的一道题,最长回文子串,有多种方法。

首先介绍的一种方法是从中间向两边展开。注意区分aba和abba型的回文串;如果当前最长的子串已经当于两边中最长的子串了,则无需再去判断。

//从中间向两边展开
      string expandAroundCenter(string s, int c1, int c2)
      {
          int l = c1, r = c2;
          int n = s.length();

          while (l >= 0 && r <= n - 1 && s[l] == s[r])
          {
              l--;
              r++;
          }
          return s.substr(l + 1, r - l - 1);
      }

      string longestPalindString(string s)
      {
          int n = s.length();
          if (n == 0)return s;

          string longest = s.substr(0, 1);
          int mid = n / 2;
          //
          for (int i = 0; i < n - 1; i++)
          {
              //如果剩下的字串长度已经小于当前最大长度字串的长度,则无需再比较
              if (2 * (mid - i + 1) < longest.length() && 2 * (n - mid - i)<longest.length())
                  break;
              //如果是aba型的回文串
              string p1 = expandAroundCenter(s, mid+i, mid+i);
              if (p1.length()>longest.length())
                  longest = p1;

              string p2 = expandAroundCenter(s, mid - i, mid - i);
              if (p2.length()>longest.length())
                  longest = p2;
              //如果是abba型的回文串
              string p3 = expandAroundCenter(s, mid+i, mid+i + 1);
              if (p3.length()>longest.length())
                  longest = p3;

              string p4 = expandAroundCenter(s, mid - i, mid - i - 1);
              if (p4.length()>longest.length())
                  longest = p4;
          }

          return longest;
      }
View Code

 还有一种动态规划的方法,第一次接触,还需慢慢理解。

string longestPalindString(string s)
      {
          const int n = s.size();
          bool f[n][n];

          fill_n(&f[0][0], n*n, false);

          int max_length = 1, start = 0;

          for (int i = 0; i < n; i++)
          {
              f[i][i] = true;
              for (int j = 0; j < i; j++)
              {
                  f[j][i] = (s[j] == s[i] && (i - j < 2 || f[j + 1][i - 1]));
                  if (f[j][i] && max_length < (i - j + 1))
                  {
                      max_length = i - j + 1;
                      start = j;
                  }
              }
          }
          s.substr(start, max_length);
      }
View Code

 

posted @ 2016-05-24 15:07  牧马人夏峥  阅读(168)  评论(0编辑  收藏  举报