题解 | #密码截取#

密码截取

http://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            String s = scan.nextLine();
            System.out.println(longestPalindrome(s));
        }
    }
    public static int longestPalindrome(String s) {
        int res = 0;
        for (int i = 0; i < s.length(); i++) {
            res = Math.max(res, extend(s, i, i));
            res = Math.max(res, extend(s, i, i + 1));
        }
        return res;
    }
    public static int extend(String s, int left, int right) {
        while (left >= 0 && right < s.length()) {
            if (s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            }else {
                break;
            }
        }
        return right - left - 1;
    }
}
全部评论

相关推荐

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