5 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*n)

    public String longestPalindrome(String s) {
        int max = Integer.MIN_VALUE;
        String result = "";
        for (int i = 0; i < s.length(); i++){
            String temp = expandFromCenterToEdge(s, i, i);
            if (max < temp.length()){
                max = temp.length();
                result = temp;
            }

            temp = expandFromCenterToEdge(s, i, i+1);
            if (max < temp.length()){
                max = temp.length();
                result = temp;
            }
        }
        return result;
    }

    private String expandFromCenterToEdge(String s, int l, int r) {
        int left = l;
        int right = r;
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
            left --;
            right ++;
        }
        return s.substring(left + 1, right);
    }


你可能感兴趣的:(LeetCode,回文串)