最长回文子串

给定一个字符串,计算该字符串的最长回文子串。

方法1:

枚举所有子串,逐一判断各个子串是否是回文


/*
 *Created on 2015年12月23日
 *Copyright 2015 Yong Cai Limited crop. All Rights Reserved
 *
 */

public class LongestPalindrome{

    public static void main(String[] args) {
        String input = "ceuvhiwfw 6412345678900009876543212841upwsv,";

        System.out.println(CollectionShuffle.compute(input));

    }

    public static String compute(String input) {

        char[] inputArray = input.toCharArray();
        int len = inputArray.length;

        int finalStart = 0, finalEnd = 0, finalLength = 0;
        //从长到短生成子串
        for (int i = 0; i < len; i++) {
            for (int start = 0, end = len - i - 1; end < len; start++, end++) {
                //对每一个子串,判断是否是回文
                for (int m = start, k = end; m <= k; m++, k--) {
                    if (inputArray[m] != inputArray[k]) {
                        break;
                    } else {
                        if (m == k || m == (k - 1)) {
                            if ((end - start) > finalLength) {
                                finalStart = start;
                                finalEnd = end;
                                finalLength = end - start;
                                //后面生成的子串长度小于已经求得最长回文长度,则可以终止计算
                                if (finalLength > (end - start)) {
                                    return input.substring(finalStart,
                                            finalEnd + 1);
                                }
                            }
                        }
                    }
                }
            }
        }
        return input.substring(finalStart, finalEnd + 1);
    }

}


输入1:ceuvhiwfw 6412345678900009876543212841upwsv,

输出1:1234567890000987654321

输入2:cuhfqwertyuiopoiuytrewqieuhf

输出2:qwertyuiopoiuytrewq





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值