zoukankan      html  css  js  c++  java
  • LeetCode "Longest Palindromic Substring" revisited

    Just reimplemented the solution to this classic problem using Manacher algorithm in my mind. So neat idea :)

    class Solution {
    public:
        string longestPalindrome(string s) 
        {    
            size_t slen = s.length();
            if (slen < 2) return s;
    
            //    inserting tokens to original string
            string ns = "#";
            for (auto c : s)
            {
                ns += c;
                ns += "#";
            }
    
            //
            size_t len = ns.length();
            vector<size_t> rec(len, 0);
    
            int maxi = 1, maxr = 0;
            int ci = 1, r = 0;
            for (size_t i = 1; i < len; i++)
            {            
                int myr = 0;        //    brand new index
                if (i <= (ci + r))    //    can be reused due to symmetry
                {                
                    myr = std::min(rec[2 * ci - i], (ci + r) - i);
                }
                //    expand to new inx towards end of string
                bool bMis = false;
                int max_ex = std::min(len - 1 - i, i);
                while (myr < max_ex)
                {
                    myr++;
                    if (ns[i + myr] != ns[i - myr])
                    {
                        bMis = true;
                        break;
                    }
                }
                if (bMis) myr--;
                
                //    book-keeping
                rec[i] = myr;
                if ((i + myr) > (maxi + maxr))
                    ci = i, r = myr;
    
                if (myr > maxr)    //     record max
                {
                    maxi = i, maxr = myr;
                }
            }
    
            string raw = ns.substr(maxi - maxr, maxr * 2 + 1);
            string ret;
            for (auto c : raw)
            {
                if (c != '#') ret += c;
            }
            return ret;
        }
    };
  • 相关阅读:
    cocoapods使用遇到的一些问题
    so
    UITextField的各种属性方法介绍
    <<第1章 初识JAVA>>
    《第16章 复习》
    《第17章 图书管理系统》
    《第15章 字符串》
    《第13章 猜拳游戏》
    《第14章 带参数的方法》
    《第12章 类的无参方法》
  • 原文地址:https://www.cnblogs.com/tonix/p/4132713.html
Copyright © 2011-2022 走看看