题解 | #最长回文子串#

最长回文子串

https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507

import java.util.Scanner;
//方法一:
//逐个遍历字符串元素,从当前字符向两端移动判断是不是回文
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int len = str.length();
        int max = 0;
        for(int i=0;i<len;i++){
            //回文串长度为奇数的情况
            max = Math.max(countPalindrome(str,i,i),max);
            //回文串长度为偶数的情况
            max = Math.max(countPalindrome(str,i,i+1),max);
        }
        System.out.println(max);
        
    }
    public static int countPalindrome(String str, int start,int end){
        
        int count = 0;
        while(start>=0&&end<str.length()&&str.charAt(start)==str.charAt(end)){
            if(start == end) //回文串长度为奇数,最中间为一个字符
                count++;
            else
                count+=2;
            start--;
            end++;
        }
        return count;
        

    }
}

全部评论

相关推荐

05-19 16:41
复旦大学 Python
ynq2126:我一直觉得现在考算法题没啥意义 真要选拔人才不如把公司实际项目中遇到的问题当成一系列场景题抛给求职者答 这才是能检测能力的东西
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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