先贴下代码,等有空再把题目补上。
双节棍字符串 : 形如 “aaa....bb....aaa” 左右两端为相同的字符,且数量相等,中间为另一重复的字符串
比如 输入 AAABDDDKDDDL 输出DDDKDDD
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str=in.nextLine();
char [] ch=str.toCharArray();
int one=0;
Character oneChar=ch[0];
int two=0;
Character twoChar=null;
int three=0;
Character threeChar=null;
String result=null;
int sum=0;
for (int i = 0; i < ch.length; i++) {
if(i==0||(ch[i]==oneChar&&ch[i]==ch[i-1]&&oneChar!=threeChar)) {
one++;
}else if(twoChar==null) {
twoChar=ch[i];
two++;
}else if(twoChar==ch[i]&&ch[i]==ch[i-1]) {
two++;
}else if(threeChar==null) {
threeChar=ch[i];
three++;
}else if(threeChar==ch[i]&&ch[i]==ch[i-1]) {
three++;
}else {
oneChar=twoChar;
one=two;
twoChar=threeChar;
two=three;
threeChar=ch[i];
three=1;
}
if(one==three&&two<one) {
if(one*2+two>sum) {
StringBuilder sb=new StringBuilder();
for (int j = 0; j < one; j++) {
sb.append(oneChar);
}
for (int j = 0; j < two; j++) {
sb.append(twoChar);
}
for (int j = 0; j < one; j++) {
sb.append(threeChar);
}
sum=one*2+two;
result=sb.toString();
oneChar=threeChar;
one=three;
twoChar=null;
two=0;
threeChar=null;
three=0;
}
}
}
System.out.println(result);
}
}