NC17 最长回文子串

牛客华为机试题库【题号 HJ开头】(重点看)
牛客在线编程算法篇【题号NC开头】
剑指offer【题号 JZ开头】
力扣

1)原题链接

2)已有题解

3)代码

package src.main.java.doublepoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import static java.lang.System.in;

/**
 * NC17 最长回文子串
 */
public class NC17LongestPalindrome {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(in));
        String str = bf.readLine();
        bf.close();

        int longestPalindrome = getLongestPalindrome(str);
        System.out.println(longestPalindrome);
    }

    public static int getLongestPalindrome(String A) {
        int max = 0;

        int len = A.length();
        //暴力解法
        for (int i = 0; i < len; i++) {
            for (int j = i + 1; j <= len; j++) {
                String subStr = A.substring(i, j);//确定字符
                if (isPalindrome(subStr) && subStr.length() > max) {
                    max = subStr.length();//最大长度
                }
            }
        }

        return max;
    }

    /**
     * 判断子串是不是回文子串
     */
    public static boolean isPalindrome(String s) {
        // abcba  奇数时 5/2=2 范围for (int i = 0; i < 2; i++) [0 1] 2 3 4
        // abccba 偶数时 6/2=3 范围for (int i = 0; i < 3; i++) [0 1 2] 3 4 5
        int strLength = s.length();
        for (int i = 0; i < strLength / 2; i++) {
            // 数组折叠对应下标相加为strLength - 1
            if (s.charAt(i) != s.charAt(strLength - 1 - i))//不相等
                return false;
        }
        return true;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值