题解 | #HJ032 密码截取#

密码截取

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

import java.util.Scanner;

/**
 * HJ32 密码截取
 */
public class HJ032 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //中心扩散法
        while (sc.hasNext()) {
            String str = sc.nextLine();
            int max = 0;
            for (int i = 0; i < str.length() - 1; i++) {
                //ABA型
                int len1 = longest(str, i, i);
                //ABBA型
                int len2 = longest(str, i, i + 1);
                max = Math.max(max, len1 > len2 ? len1 : len2);
            }
            System.out.println(max);
        }
        sc.close();
    }

    private static int longest(String str, int i, int j) {
        while (j < str.length() && i >= 0 && str.charAt(i) == str.charAt(j)) {
            i--;
            j++;
        }
        return j - i - 1;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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