算法5:给定一个字符串S 找到字符串S中最长的回文子串

给定一个字符串S 找到字符串S中最长的回文子串

package com.jy.leetcode;

/**
 * @author t
 * @version 1.0
 * @date 2020/5/7 15:20
 * @company juya
 */
public class LettCode5 {
    //给定一个字符串S  找到字符串S中最长的回文子串。假设S的最大长度为1000
    //输入 babad  输出 bab  /  aba
    //输入 cbbd   输出 bb
    public static void main(String[] args) {
        String s = "babad";
        String palindrome = getPalindrome(s);
        System.out.println(palindrome);
    }

    public static String getPalindrome(String s) {
        if (s == null || s.length() < 1) {
            return "";
        }
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = expandAroundCenter(s, i, i);
            int len2 = expandAroundCenter(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    private static int expandAroundCenter(String s, int left, int right) {
        int L = left, R = right;
        while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
            L--;
            R++;
        }
        return R - L - 1;
    }
}

你可能感兴趣的:(算法)