LeetCode每日一题: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.

问题分析

我们可以采用递归的方式,找每个字符为中心的最长回文子串,用一个全局变量(写代码应该尽量避免全局的变量)来记录最长回文子串的起始点和长度,递归时要分子串字符数是奇数还是偶数分类讨论。

代码实现

public String longestPalindrome(String s) {
        if (s.length() < 2) return s;
        for (int i = 0; i < s.length() - 1; i++) {
            findLongestPalindrome(s, i, i);
            findLongestPalindrome(s, i, i + 1);
        }
        return s.substring(startInLongestPalindrome, startInLongestPalindrome + maxLenInLongestPalindrome);
    }

    private void findLongestPalindrome(String s, int i, int j) {
        while (i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j)) {
            i--;
            j++;
        }
        if (maxLenInLongestPalindrome < j - i - 1) {
            startInLongestPalindrome = i + 1;
            maxLenInLongestPalindrome = j - i - 1;
        }
    }

    private int startInLongestPalindrome = 0, maxLenInLongestPalindrome = 0;

你可能感兴趣的:(LeetCode每日一题:longest palindromic substring)