题解 | #最长回文子串#

最长回文子串

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s;
        while ((s = br.readLine()) != null) {
            int res = Integer.MIN_VALUE;
            for (int i = 0; i < s.length(); i++) {
                int len1 = getLong(s, i, i);
                int len2 = getLong(s, i, i + 1);
                int len = Math.max(len1, len2);
                res = len > res? len : res;
            }
            System.out.println(res);
        }
        
    }
    // 中心扩展算法
    public static int getLong(String s, int left, int right) {
       while (left >= 0 && right <= s.length()-1 && s.charAt(left) == s.charAt(right)) {
           left--;
           right++;
       }
        return right - left - 1;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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