题目描述
Catcher 是MCA国的情报员,他工作时发现敌国会用一些对称的密码进行通信,比如像这些ABBA,ABA,A,123321,但是他们有时会在开始或结束时加入一些无关的字符以防止别国破解。比如进行下列变化 ABBA->12ABBA,ABA->ABAKK,123321->51233214 。因为截获的串太长了,而且存在多种可能的情况(abaaab可看作是aba,或baaab的加密形式),Cathcer的工作量实在是太大了,他只能向电脑高手求助,你能帮Catcher找出最长的有效密码串吗?
(注意:记得加上while处理多个测试用例)
输入描述:
输入一个字符串
输出描述:
Catcher 是MCA国的情报员,他工作时发现敌国会用一些对称的密码进行通信,比如像这些ABBA,ABA,A,123321,但是他们有时会在开始或结束时加入一些无关的字符以防止别国破解。比如进行下列变化 ABBA->12ABBA,ABA->ABAKK,123321->51233214 。因为截获的串太长了,而且存在多种可能的情况(abaaab可看作是aba,或baaab的加密形式),Cathcer的工作量实在是太大了,他只能向电脑高手求助,你能帮Catcher找出最长的有效密码串吗?
(注意:记得加上while处理多个测试用例)
输入描述:
输入一个字符串
输出描述:
返回有效密码串的最大长度
思路一:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String str = scanner.next();
int max = 1;
for (int i = 1; i < str.length() - 1; i++)
{
int m = i - 1;
int n = i + 1;
int count = 0;
while (m >= 0 && n < str.length())
{
if (str.charAt(m) == str.charAt(n))
{
count++;
m--;
n++;
}
else
break;
}
max = max >= (count * 2 + 1) ? max : (count * 2 + 1);
}
for (int i = 1; i < str.length(); i++)
{
int m = i - 1;
int n = i;
int count = 0;
while (m >= 0 && n < str.length())
{
if (str.charAt(m) == str.charAt(n))
{
count++;
m--;
n++;
}
else
break;
}
max = max >= (count * 2) ? max : (count * 2);
}
System.out.println(max);
}
}
}
思路二:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String str = scanner.next();
StringBuffer sb = new StringBuffer(str);
String rev = sb.reverse().toString();
System.out.println(getMax(str, rev));
}
}
public static int getMax(String str, String rev)
{
for (int len = str.length(); len >= 1; len--)
{
for (int i = 0; i <= str.length() - len; i++)
{
String sub = rev.substring(i, i + len);
if (str.contains(sub))
return len;
}
}
return 1;
}
}