题解 | #最长回文子串# 中心对称法,其中注意两种情况

最长回文子串

https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param A string字符串 
     * @return int整型
     */
    public int getLongestPalindrome (String A) {
        // write code here

        int lenA=0;
        int lenB=0;
        int max=0;
        int result=0;
            for(int i=0;i<A.length();i++){
                lenA = findTheLengthOfPalindrome(A,i,i);//这种情况是左右对称中间为空
                lenB = findTheLengthOfPalindrome(A,i,i+1);//这种情况是中间有一个中心轴字符
                max = Math.max(lenA,lenB);
                result = Math.max(max,result);
            }

           return result;
    }

    public int findTheLengthOfPalindrome(String str,int left,int right){
           while(left>=0&&right<=str.length()-1&&str.charAt(left)==str.charAt(right)){
               left--;
               right++;
           }

           return right-left-1;


    }
}

全部评论

相关推荐

渴望wlb的牛油果很...:直说卡第一学历不就行了 非得拐弯抹角
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务