牛客网

彩色宝石项链 

解法一是错误的,因为定义pos数组后,对其进行赋值产生了混乱;解法二是AC了,不知道是不是因为对数组进行赋值的原因。

解法一错误: 

import java.lang.reflect.Array;
import java.util.*;
public class Main1 {public static int flag=1;public static void main(String args[]){Scanner in=new Scanner(System.in);while(in.hasNext()){String str=in.nextLine();System.out.println(f1(str));}}public static int f1(String str){if(str.length()<=5){return 0;}else{char ch[]=new char[]{'A','B','C','D','E'};List<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();for(int i=0;i<ch.length;i++){List<Integer> temp3=new ArrayList<Integer>();for(int j=0;j<str.length();j++){if(ch[i]==str.charAt(j)){temp3.add(j);}}list.add(new ArrayList(temp3));}int res=0;int pos[]=new int[5];for(int i0=0;i0<list.get(0).size();i0++){pos[0]=list.get(0).get(i0);for(int i1=0;i1<list.get(1).size();i1++){pos[1]=list.get(1).get(i1);for(int i2=0;i2<list.get(2).size();i2++){pos[2]=list.get(2).get(i2);for(int i3=0;i3<list.get(3).size();i3++){pos[3]=list.get(3).get(i3);for(int i4=0;i4<list.get(4).size();i4++){pos[4]=list.get(4).get(i4);res=Math.max(res,f2(pos,str));}}}}}return res;}}public static int f2(int pos[],String str){int pos2[]=new int[5];for(int i=0;i<5;i++)pos2[i]=pos[i];Arrays.sort(pos);int dmax=(str.length()-1-pos[4])+(pos[0]-0);for(int i=0;i<=3;i++){dmax=Math.max(dmax,pos[i+1]-pos[i]-1);}return dmax;}
}

 

解法二:

import java.lang.reflect.Array;
import java.util.*;
public class Main {public static int flag=1;public static void main(String args[]){Scanner in=new Scanner(System.in);while(in.hasNext()){String str=in.nextLine();System.out.println(f1(str));}}public static int f1(String str){if(str.length()<=5){return 0;}else{char ch[]=new char[]{'A','B','C','D','E'};List<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();for(int i=0;i<ch.length;i++){List<Integer> temp3=new ArrayList<Integer>();for(int j=0;j<str.length();j++){if(ch[i]==str.charAt(j)){temp3.add(j);}}list.add(new ArrayList(temp3));}int res=0;for(int i0=0;i0<list.get(0).size();i0++){for(int i1=0;i1<list.get(1).size();i1++){for(int i2=0;i2<list.get(2).size();i2++){for(int i3=0;i3<list.get(3).size();i3++){for(int i4=0;i4<list.get(4).size();i4++){int pos[]=new int[5];pos[0]=list.get(0).get(i0);pos[1]=list.get(1).get(i1);pos[2]=list.get(2).get(i2);pos[3]=list.get(3).get(i3);pos[4]=list.get(4).get(i4);res=Math.max(res,f2(pos,str));}}}}}return res;}}public static int f2(int pos[],String str){int pos2[]=new int[5];for(int i=0;i<5;i++)pos2[i]=pos[i];Arrays.sort(pos);int dmax=(str.length()-1-pos[4])+(pos[0]-0);for(int i=0;i<=3;i++){dmax=Math.max(dmax,pos[i+1]-pos[i]-1);}return dmax;}
}