今天把字符串的完美度搞定了,啊,期间遇到很多问题,现分享一下:
我做字符串完美度的的思路分为好几个方案,不过目前只有一个实现了,现在把这个思路贴出来
总的思路:
先将字符串进行拆分为一个字符数组,然后对每个字符出现的次数进行统计,然后按照次数的多少从26开始逐步的进行
赋值,接下来就可以进行计算完美值了。
把代码贴出来:
public static int perfect(String s){
char[]array=s.toCharArray();//用于获取每个字符
int maxValue=26;//字符中值最大时的情况
int perfectSum=0;//保存完美值
System.out.println("元素的个数为:"+array.length);
//简历三个list集合一个保存第一次遇到的字符,一个保存期对应的值,一个用于保存期出现的次数,这三个list集合值是想对应的
List<Character> listChar=new ArrayList<Character>();
List<Integer> listValue=new ArrayList<Integer>();
List<Integer> listCount=new ArrayList<Integer>();
boolean flage=false;
//先将每个字符的出现次数保存,然后根据次数进行分配值,然后再循环所有字符进行计算完美值
for(int i=0;i<array.length;i++){
for(int f=0;f<listChar.size();f++){
Character yizhi=listChar.get(f);
if(yizhi.charValue()==Character.toLowerCase(array[i])){
// System.out.println("值有相同的为:"+array[i]);
flage=true;
listCount.set(f,new Integer(listCount.get(f).intValue()+1));
break;
}
else
flage=false;
}
if(!flage){
int value=1;
char change=Character.toLowerCase(array[i]);
listChar.add(new Character(change));
listCount.add(new Integer(value));
}
}
//对相应的listValue赋初值
for(int q=0;q<listChar.size();q++)
listValue.add(new Integer(0));
int max=0;//保存出现次数最多的值
int maxId=0;//保存出现次数最多值得Id
//进行对listValue进行赋值(是相应的字符(listChar)对应的值,根据listCount中的值由大到小进行分配)
for(int r=0;r<listCount.size();r++){
for(int t=0;t<listCount.size();t++){
if(((max<=listCount.get(t).intValue())&&((listValue.get(t))==0))||((max<=listCount.get(t).intValue())&&r==0)){
maxId=t;
max=listCount.get(maxId).intValue();
}
}
listValue.set(maxId,maxValue--);
max=0;
maxId=0;
}
//进行计算perfect值
for(int p=0;p<listChar.size();p++){
perfectSum=perfectSum+(listCount.get(p).intValue())*(listValue.get(p).intValue());
}
return perfectSum;
}
思想总结:
1.对于每个问题的解决必须有一个清晰的解决方案,然后按方案进行编程
2.对于调试程序,一定要先进行静态调试,自己先分析,这样会使自己发现方案中不足
java知识总结:
1.要学会看jdk的文档,当然得有一定的英文基础(我的就不是很好)
2.list集合其类型中必须是引用,不能是基本类型
1259

被折叠的 条评论
为什么被折叠?



