LeetCode5 最长回文串

LeetCode 5 最长回文串

原题

思路:
回文串分为两种:奇数长度和偶数长度
分别进行判断就好了。基准点左和右的字符相等

package com.java.leetcode;

/**
 * @author dengtiantian
 */
public class Question5 {
    static class Solution {
        /**
         * @author dengtiantian
         * 5 最长回文串
         * 回文串可以是长度有奇数形式,也有偶数形式
         */
        public String longestPalindrome(String s) {
        	// 输入为空的情况
            if (s.length()==0){
                return s;
            }
            // 最大长度
            int maxLength = 1;
            String maxString = s.substring(0,1);
            // 这里i指定奇数回文串中心的下标。 或者偶数回文串 中心左节点的下标
            for (int i = 0; i < s.length();i++){
                // 偶数回文串
                int intTemp = 0;
                while (i-intTemp>=0 && i+1+intTemp<s.length()){
                    if (s.charAt(i-intTemp) == s.charAt(i+1+intTemp)){
                        int strLength = i+1+intTemp-(i-intTemp)+1;
                        if (maxLength < strLength){
                            maxLength = strLength;
                            maxString = s.substring(i-intTemp,i+1+intTemp+1);
                        }
                        intTemp++;
                    }else {
                        break;
                    }

                }

                // 奇数回文串
                int intTemp2 = 1;
                while (i-intTemp2>=0 && i+intTemp2<s.length()){
                    if (s.charAt(i-intTemp2) == s.charAt(i+intTemp2)){
                        int strLength = i+intTemp2 - (i-intTemp2) +1;
                        if (maxLength < strLength){
                            maxLength = strLength;
                            maxString = s.substring(i-intTemp2,i+intTemp2+1);
                        }
                        intTemp2++;
                    }else {
                        break;
                    }

                }

            }

            return maxString;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        String str = solution.longestPalindrome("cbbd");
        System.out.println(str);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值