Leetcode5 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.

Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:
Input: "cbbd"
Output: "bb"

Approach 1: Expand Around Center

So, What exactly is a Palindrome, which is a string that is the same boards as above, it is in Reverse so if we look at "bab", we will see that "bab" would be the same it was spelled forwards or backward. This place we can find that if we read any word like "abb" from left to right, is the same as read from right to left.
So. it has two criteria:
(1) the first Character = the Last Character;
(2) the inner word is also Palindromic;

So if you are ready to solve this problem I encourage you to try it on your own first but if you are ready to get started come with me to the follows coding.

So, to solve this problem we are going to use the idea of expending around the center of a palindrome, as you can see here, I have two different types of palindromes, one of these is an odd length, like "aba", and the other is an even length palindrome, likes "abba". So, to expand on the center, we need to define exactly what the center of a palindrome is. So we look here at the odd length palindrome "aba", the center of this palindrome is "b", and if we expand from the center out, we can check to see if the characters on either side that are mirroring each other are equal and if they are, we can increase the length of our palindrome in the odd lengths palindrome, the center of a palindrome is an individual character but in an even length palindrome we can see that the center is not a character but is the space between two characters. So the center and even length palindrome would like here between these two characters. And to expand around the center we would expand from between these two characters checking to see if 'b' and 'b' are equal, they are and expand again to check to see if 'a' and 'a' are equal they are and increase the length of our palindrome this way, so now that we know how to expand from the center and check for the size of a palindrome. Let's go through a quick example of using this strategy to solve this problem.

To solve this problem, we are going to initialize a result to zero and we are going to iterate through this string checking each character and space between the characters for the center of a palindrome, we are going to keep track of our longest palindrome and return the length of the longest palindrome at the end. In this problem, we are just going to be tracking the total length, but you could see that using this algorithm you can easily adapt it to returning the string which is what the prompt and the question is asking.

In fact, we could solve it in O(n^2) time using only constant space.

We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n - 1 such center.

You might be asking why there are 2n - 1 but not n centers? The reason is the center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as "abba") and its center is between the two 'b's.

// Time complexity : O(n^2). Since expanding a palindrome around its center could take O(n) time, the overall complexity is O(n^2).
// Space complexity : O(1).

class Solution{
    // Initialize a global variable;
    String res = "";
    public String longestPalindrome(String s) {
        //corner case;
        if(s == null || s.length() < 2) {
            return s;
        }
        for(int i = 0; i < s.length(); i++) {
            helper(s, i, i); // the center is odd length; assume odd length, try to extend Palindrome as possible
            helper(s, i, i + 1); // the center is even length;
        }
        return res;
    }
    public void helper(String s, int left, int right) {
        while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        String cur = s.substring(left + 1, right);
        if(cur.length() > res.length()) {
            res = cur;
        }
    }
}

Approach 2: Dynamic Programming

it has two criteria:
(1) the first Character = the Last Character;
(2) the inner word is also Palindromic;

Firstly, we need to introduce the variable, it is a boolean two-dimensional variable, likes:
boolean[ ][ ] isPalindrome;
isPalindrome[i][j] means from index i character to index j character; if it is true, so it is a palindrome string, otherwise, it is not a palindrome string;
Thus, transfer to the machine language:

like " a b b a"
       i     j

(1). s.charAt(i) == s.charAt(j);
(2). isPalindrom[i + 1][j - 1] = true || j - i <= 2;

As we just indicate to use the dynamic programming technique, we will introduce a two-dimensional boolean array that is called isPalindrom;

//  Time complexity : O(n^2) This gives us a runtime complexity of O(n^2).
// Space complexity : O(n^2) It uses O(n^2)space to store the table.
class Solution {
    public String longestPalindrome(String s) {
        int len = s.length();
        // corner case
        if(s == null || len < 2) return s;
        
        boolean[][] isPalindrome = new boolean[len][len];
        
        int left = 0;
        int right = 0;
        
        for(int j = 1; j < len; j++) {
            for(int i = 0; i < j; i++) {
                //The code j - i <= 2 is checking whether the inner word between string.charAt(i) and string.charAt(j) only has at most one character. If only has just one character, the inner world is palindromic
                //i is the index for left character and j is the index for the right character. isPalindrome[i + 1][j - 1] is a boolean indicating whether the inner word is palindromic or not. When isPalindrome[i + 1][j - 1] is true, it means the word of i +1 to  j - 1 characters of the string is palindromic.
                boolean isInnerWordPalindrom = isPalindrome[i + 1][j - 1] || (j - i <= 2);
                if(s.charAt(i) == s.charAt(j) && isInnerWordPalindrom) {
                    isPalindrome[i][j] = true;
                    if(j - i > right - left) {
                        //we need to find the maximum palindrome
                        left = i;
                        right = j;
                    }
                }
            }
        }
        return s.substring(left, right + 1);
        // in the java, the substring inclusive the left character but exclusive the right character, so we need plus one on the right index.
    }
}

Approach 3: Manacher's Algorithm:

There is even an O(n) algorithm called Manacher's algorithm, explained. However, it is a non-trivial algorithm, and no one expects you to come up with this algorithm in a 45 minutes coding session. But, please go ahead and understand it, I promise it will be a lot of fun.

class Solution {
   
    // process the t String; 
    public String longestPalindrome(String s) {
        if(s == null || s.length() < 2) {
            return s;
        }
        char[] t = new char[s.length() * 2 + 1]; //transformed string
        int[] p = new int[t.length]; // p[i] is radius length of longest Palindromic string centered at i;
        preprocess(s, t);
        int center = 0, right = 0;
        for(int i = 1; i < t.length - 1; i++) {
            int mirror = 2 * center - i; //center - mirror = i - center,  mirror is i's mirror based on center
            // if i within pre-calculated palindrome 
            p[i] = right > i ? Math.min(p[mirror], right - i) : 1;
            while(i + p[i] < t.length && i - p[i] >= 0 && t[i + p[i]] == t[i - p[i]]) p[i]++;
            if(i + p[i] > right) {
                center = i;
                right = i + p[i];
            }
        }
        center = 0;
        int maxLen = 0;
        for(int i = 1; i < p.length - 1; i++) {
            if(p[i] > maxLen) {
                center = i;
                maxLen = p[i];
            }
        }
        return s.substring((center - maxLen + 2) / 2, (center + maxLen) / 2);
    }
    private void preprocess(String s, char[] t) {
        // Insert "#"
        for(int i = 0; i < s.length(); i++) {
            t[2 * i] = '#';
            t[2 * i + 1] = s.charAt(i);
        }
        t[t.length - 1] = '#';
    }
    
}

参考:
https://www.jianshu.com/p/238fa31f0999
https://segmentfault.com/a/1190000008484167?utm_source=tag-newest
https://www.cnblogs.com/grandyang/p/4475985.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353

推荐阅读更多精彩内容