5. Longest Palindromic Substring (二)

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.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:

Input: "cbbd"
Output: "bb"
上一篇文章已经给出了最容易想到的思路——穷举法,虽然在实现的过程中是最容易的,但是当性能无法满足业务的需求时,就需要找到更快捷的方法。

首先随便写两个回文,寻找他们之间的规律

str1: "aszzsdds 1 2 3 3 2 1 asddas"

str2: "aqweq 1 2 3 4 3 2 1 zdssa"

在"str1"中,最长的回文是123321,而在"str2"中,最长的回文1234321,我们可以看出,在一串回文的最中心一直往外,都是一一对应的一组字符。

那么反之,如: str3: "acdcba"

如果str3[0] != str3[1] && str3[0] != str3[2] 那么我们可以认为以索引0为中心的回文是不存在的

public static String longestPalindrome(String s) {
        if (s.length() < 2) return s;

        char[] charArray = s.toCharArray();
        int resultSize = 0;
        int leftIndex = 0;
        for (int i = 0; i < charArray.length; i++) {
            int len1 = checkPalindrome(charArray, i , i+1);
            if (len1 > resultSize){
                resultSize = len1;
                leftIndex = i - (len1 - 1) / 2;
            }
            
            int len2 = checkPalindrome(charArray, i , i+2);
            if (len2 > resultSize){
                resultSize = len2;
                leftIndex = i + 1 - len2 / 2;
            }
        }
        return s.substring(leftIndex, leftIndex + resultSize);
    }

    private static int checkPalindrome(char[] charArray, int j, int k){
        while (j >= 0 && k < charArray.length && charArray[j] == charArray[k]){
            j--;
            k++;
        }
        return k - j - 1;
    }
点击可以查看更多解法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值