【Leetcode】Longest Palindromic Substring

题目链接:https://leetcode.com/problems/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.

思路:

遍历该字符串每一个位置,并判断以该位置为中位点的最长回文串的长度,复杂度为O(n^2)。 要注意如果回文串是奇数长度和偶数长度不同。所以需要遍历判断两次。一次默认该点为中心的回文串是奇数长,一次默认是偶数长。

算法:

public String longestPalindrome(String s) {  
        if (s.length() <= 1) {  
            return s;  
        }  
        if (s.length() == 2) {  
            if (s.charAt(0) == s.charAt(1)) {  
                return s;  
            } else {  
                return s.charAt(0) + "";  
            }  
        }  
  
        String res = "";  
        int maxLen = 0;  
        // 对奇位点判断  
        for (int i = 1; i < s.length() - 1; i++) {  
            String str = calPalin(s, i - 1, i + 1);  
            if (maxLen < str.length()) {  
                maxLen = str.length();  
                res = str;  
            }  
        }  
  
        // 对偶位点判断  
        for (int i = 1; i < s.length(); i++) {  
            String str = calPalin(s, i - 1, i);  
            if (maxLen < str.length()) {  
                maxLen = str.length();  
                res = str;  
            }  
        }  
  
        return res;  
    }  
  
    public String calPalin(String s, int left, int right) {  
        if (left < 0 && right >= s.length()) {  
            return "";  
        }  
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {  
            left--;  
            right++;  
        }  
        return s.substring(left + 1, right);  
    }  


你可能感兴趣的:(【Leetcode】Longest Palindromic Substring)