筆試題--字符串處理(3)
/**
* Catcher是MCA國的情報員,他工作時發現敵國會用一些對稱的密碼進行通信,
* 比如像這些ABBA,ABA,A,123321,但是他們有時會在開始或結束時加入一些無關的字符以防止別國破解。
* 比如進行下列變化 ABBA->12ABBA,ABA->ABAKK,123321->51233214 。
* 因爲截獲的串太長了,而且存在多種可能的情況(abaaab可看作是aba,或baaab的加密形式),
* Cathcer的工作量實在是太大了,他只能向電腦高手求助,你能幫Catcher找出最長的有效密碼串嗎?
輸入:
字符串-密碼內容
輸出:
整形數-有效密碼串最大長度
樣例輸入:
ABBA
樣例輸出:
4
*/
import java.util.Scanner;
public class InterceptPassword {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
sc.close();
char[] ch=str.toCharArray();
System.out.println(subPWD(ch));
}
public static int subPWD(char[] ch)
{
int max=1;
int ind=0;
char[] ch2=new char[ch.length];
for(int i=ch.length-1;i>=0;i--)
{
ch2[ind++]=ch[i];
}
for(int m=0;m<ch.length;m++)
{
for(int n=0;n<ch.length;n++)
{
if(ch[m]==ch2[n])
{
int count=1;
int l=m;
int k=n;
while(l<ch.length-1&&k<ch.length-1)
{
if(ch[++l]==ch2[++k])
{
count++;
}
else
{
break;
}
}
if(count>max)
{
max=count;
}
}
}
}
return max;
}
}
* Catcher是MCA國的情報員,他工作時發現敵國會用一些對稱的密碼進行通信,
* 比如像這些ABBA,ABA,A,123321,但是他們有時會在開始或結束時加入一些無關的字符以防止別國破解。
* 比如進行下列變化 ABBA->12ABBA,ABA->ABAKK,123321->51233214 。
* 因爲截獲的串太長了,而且存在多種可能的情況(abaaab可看作是aba,或baaab的加密形式),
* Cathcer的工作量實在是太大了,他只能向電腦高手求助,你能幫Catcher找出最長的有效密碼串嗎?
輸入:
字符串-密碼內容
輸出:
整形數-有效密碼串最大長度
樣例輸入:
ABBA
樣例輸出:
4
*/
import java.util.Scanner;
public class InterceptPassword {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
sc.close();
char[] ch=str.toCharArray();
System.out.println(subPWD(ch));
}
public static int subPWD(char[] ch)
{
int max=1;
int ind=0;
char[] ch2=new char[ch.length];
for(int i=ch.length-1;i>=0;i--)
{
ch2[ind++]=ch[i];
}
for(int m=0;m<ch.length;m++)
{
for(int n=0;n<ch.length;n++)
{
if(ch[m]==ch2[n])
{
int count=1;
int l=m;
int k=n;
while(l<ch.length-1&&k<ch.length-1)
{
if(ch[++l]==ch2[++k])
{
count++;
}
else
{
break;
}
}
if(count>max)
{
max=count;
}
}
}
}
return max;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.