题解 | #最长回文子串#

最长回文子串

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

直接看就能懂
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String s = in.nextLine();
            int max = 0;
            for(int i = 1; i < s.length(); i ++){
                int findLen = Math.max(getMaxLen(s,i,i),getMaxLen(s,i,i+1)); 
                if(findLen > max) max = findLen;
            }
            System.out.println(max);
        }
    }

    public static int getMaxLen(String s,int left,int right){
        if(right >= s.length()){
            return 0;
        }
        while(left >=0 && right < s.length() && s.charAt(left) == s.charAt(right)){
            left --;
            right ++;
        }
        return right - left - 1;
    }
}

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务