• [leetcode]Longest Palindromic Substring


    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.

    #include<iostream>
    #include<string>
    using namespace std;
    class Solution {
    public:
        string preProcess(string s) {
          int n = s.length();
          if (n == 0) return "^$";
          string ret = "^";
          for (int i = 0; i < n; i++)
            ret += "#" + s.substr(i, 1);
         
          ret += "#$";
          return ret;
        }
         
        string longestPalindrome(string s) {
          string T = preProcess(s);
          int n = T.length();
          int *P = new int[n];
          int C = 0, R = 0;
          for (int i = 1; i < n-1; i++) {
            int i_mirror = 2*C-i; // equals to i' = C - (i-C)
            
            P[i] = (R > i) ? min(R-i, P[i_mirror]) : 0;
            
            // Attempt to expand palindrome centered at i
            while (T[i + 1 + P[i]] == T[i - 1 - P[i]])
              P[i]++;
         
            // If palindrome centered at i expand past R,
            // adjust center based on expanded palindrome.
            if (i + P[i] > R) {
              C = i;
              R = i + P[i];
            }
          }
         
          // Find the maximum element in P.
          int maxLen = 0;
          int centerIndex = 0;
          for (int i = 1; i < n-1; i++) {
            if (P[i] > maxLen) {
              maxLen = P[i];
              centerIndex = i;
            }
          }
          delete[] P;
          
          return s.substr((centerIndex - 1 - maxLen)/2, maxLen);
        }
    };
    int main(){
    	Solution s = Solution();
    	string r = s.longestPalindrome("a");
    	cout << r << endl;
    	return 1;
    }
    

      

  • 相关阅读:
    SVN服务的配置与管理
    SVN配置多仓库与权限控制
    SVN使用详解
    这个问题他又来了,如何学编程!
    乘风破浪的程序员们
    Java 学习路线(史上最全 2020 版 ~ 持续更新中)
    P4782 【模板】2-SAT 问题
    HDU
    2020.8.3
    Interesting Computer Game
  • 原文地址:https://www.cnblogs.com/zhutianpeng/p/4240373.html
Copyright © 2020-2023  润新知