[LeetCode]Longest Palindromic Substring

The correct way is to backtrack. It is more cost-effective to judge the palindrome from the middle, because once it fails, there is no point in continuing to judge, you can back track.

So just traverse, judge from the traversed position as the center to both sides.

It should be noted that ABA ABBA is both a palindrome, the first center is B, and the second is BB (it can also be regarded as the gap between BB).

So when traversing, each position must be centered on the current letter, and then centered on the current letter and the one to the right of it. .


class Solution {
    public String longestPalindrome(String s) {

        if(s.length()==1)return s;
        int max=0;
        String res=new String();
        for (int i=0;i<s.length();i++){
            int L = i; // aba
            int R=i;
            String temp=getPlength(s,L,R);
            if(temp.length()>max){
                max=temp.length();
                res=temp;
            }
            if(i !=s.length()-1){
                L=i;R=i+1;//abba
                temp=getPlength(s,L,R);
                if (temp.length()>max){
                    max=temp.length();
                    res=temp;
                }
            }
        }
        return res;
    }
    private String getPlength(String s,int L,int R){
        while (L>=0 && R<s.length() && s.charAt(L)==s.charAt(R)){
            L--;R++;
        }
        return s.substring(L+1,R);
    }
}

Scan it and find the longest possible palindrome in each position.
Try it with single-character and double-letter as the center, and then update it.

Time: O(n^2)
Space: O(n)

public class Solution {
    public String longestPalindrome(String s) {
        if (s.length() <= 1) return s;
        String res = "";
        
        for (int i = 0; i < s.length(); i++) {
            int l = i;
            int r = i;
            
            String temp = getString(s, l, r);
            if (temp.length() > res.length()) {
                res = temp;
            }
            
            r = i + 1;
            temp = getString(s, l, r);
            if (temp.length() > res.length()) {
                res = temp;
            }
        }
        
        return res;
    }
    
    public String getString(String s, int l, int r) {
        while (l >= 0 && r < s.length()) {
            if (s.charAt(l) != s.charAt(r)) {
                break;
            } else {
                r++;
                l--;
            }
        }
        return s.substring(l+1, r);
        
        
    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325694859&siteId=291194637
Recommended