java题目HJ32 密码截取

描述

Catcher是MCA国的情报员,他工作时发现敌国会用一些对称的密码进行通信,比如像这些ABBA,ABA,A,123321,但是他们有时会在开始或结束时加入一些无关的字符以防止别国破解。比如进行下列变化 ABBA->12ABBA,ABA->ABAKK,123321->51233214 。因为截获的串太长了,而且存在多种可能的情况(abaaab可看作是aba,或baaab的加密形式),Cathcer的工作量实在是太大了,他只能向电脑高手求助,你能帮Catcher找出最长的有效密码串吗?
 
 
数据范围:字符串长度满足 1 \le n \le 2500 \1n2500 

输入描述:

输入一个字符串(字符串的长度不超过2500)

输出描述:

返回有效密码串的最大长度

示例1

输入:
ABBA
输出:
4

示例2

输入:
ABBBA
输出:
5

 

 

 1 import java.io.*;
 2 import java.util.*;
 3 
 4 public class Main {
 5     public static void main(String[] args) throws IOException {
 6         Scanner sc = new Scanner(System.in);
 7         while(sc.hasNext()) {
 8             String s = sc.nextLine();
 9             System.out.println(solution(s));
10         }
11     }
12     
13     public static int longStr(String s, int left, int right) {
14         while( left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
15             left--;
16             right++;
17         }
18         return right-left -1;
19     }
20     
21     
22     
23     public static int solution(String str) {
24         int res = 0;
25         for(int i = 0; i<str.length(); i++) {
26             //ABA型
27             int len1 = longStr(str,i,i);
28             int len2 = longStr(str,i,i+1);
29             res = Math.max(res, len1 > len2 ? len1 : len2);
30         }
31         return res;
32     }
33 }

 

posted @ 2022-03-08 21:16  海漠  阅读(108)  评论(0编辑  收藏  举报