[LeetCode]Longest Palindromic Substring 最长回文子串

正确的做法是backtrack. 回文判断从中间判断比较划算,因为一旦失败,就没有继续往外判断的意义了,可以back track。

所以就遍历,从遍历的位置为中心往两边判断。

需要注意,ABA ABBA这俩都算回文,第一个中心是B,第二个是BB(也可以看做是BB之间的空隙)。

所以遍历的时候,每个位置要先以当前字母为中心,再以当前字母和他右边那个为中心。。


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);
    }
}

扫一遍,每个位置找可能符合的最长回文。
分别以单字符和双字母作为中心都试试,然后更新就行了。

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);
        
        
    }
}


猜你喜欢

转载自blog.csdn.net/a1084958096/article/details/80223733