java面试算法题(小红的ABC)

题目描述
小红拿到了一个只包含 'a' , 'b' , 'c' 三种字符的字符串。
小红想知道,这个字符串最短的、长度超过 1 的回文子串的长度是多少?
子串定义:字符串取一段连续的区间。例如"abcca"的子串有"ab"、"bcca"等,但"aca"则不是它的子串。
回文的定义:一个字符串正着读和倒着读都是相同的,那么定义它的回文的。

输入描述:
一个只包含 'a' , 'b' , 'c' 三种字符的字符串。

数据范围:字符串长度不小于2,且不超过100

输出描述:
如果不存在长度超过1的回文子串,则输出-1。

否则输出长度超过1的最短回文子串的长度。
 

思路:

高端的结题思路往往采用最原始的办法,那就是逐段截取,然后反转对比

上代码:

import java.util.Scanner;


public class Demo{
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String line = scanner.nextLine();
        int length = line.length();

        int num = -1;

        for (int i = 0; i < length; i++) {
            for (int i1 = i+2; i1 <= length; i1++) {
                String substring = line.substring(i, i1);
                char[] chars = substring.toCharArray();
                char[] chars1 = reversalCharArr(chars);
                String oChars = new String(chars);
                String nChars = new String(chars1);
                if (oChars.equals(nChars)){
                    num = Math.max(num,oChars.length());
                }
            }
        }
        System.out.println(num);
    }

    static char[] reversalCharArr(char[] arr){
        int length = arr.length;
        char[] tempChars = new char[length];
        for (int i = 0; i < length; i++) {
            tempChars[i] = arr[length-i-1];
        }
        return tempChars;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值