题解 | #最长回文子串#

最长回文子串

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\n");
        while (scanner.hasNext()) {
            String S = scanner.next();
            int max = S.length();
            boolean A = false;
            while (max> 0) {
                int left = 0;
                int right = max - left - 1;
            
                while (right < S.length()) {
                    if (is(S, left, right)) {
                        A = true;
                        break;
                    }
                    left++;
                    right++;
                }
                if (A) {
                    System.out.println(max);
                    break;
                }
                max--;
            }
        }
    }
    public static boolean is(String S, int left, int right) {
        while (left<right) {
            if (S.charAt(left) != S.charAt(right)) return false;
            left++;
            right--;
        }
        return true;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务