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);
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37628958/article/details/105887232