读书人

找到字符串中重复最多字符

发布时间: 2012-11-09 10:18:48 作者: rapoo

找出字符串中重复最多字符

1、找出字符串中重复最多字符

?

?

//方法1、

public static void main(String[] args){

???? List list=new ArrayList();
???? Set set=new HashSet();
?????????
???? String s="anadd";

??? char[]arr=s.toCharArray();
??
??? Map map=new TreeMap();?
??? for(int i=0;i<arr.length;i++){
???? Integer value=(Integer) map.get(arr[i]);
???? if(value==null){
????? map.put(arr[i], 1);
???? }else{
????? map.put(arr[i], (Integer)map.get(arr[i])+1);
???? }
??? }
???
??? for(int i=0;i<arr.length;i++){
???? if((Integer)map.get(arr[i])!=0){
//??? 把所有的value全部放在list中。
????? list.add((Integer)map.get(arr[i]));
//??? 再对list进行排序,找到value最大的值即:list.get(list.size()-1)
????? Collections.sort(list);
//???? 过滤一下,让value最大的值,进入循环。
????? if((Integer)map.get(arr[i])==list.get(list.size()-1)){
//??? ?? 把对应的key放在set中,为了使防止重复。
??????? set.add(arr[i]);
??????
????? }
???? }
??? }
??? Iterator ite=set.iterator();
??? while(ite.hasNext()){
???? System.out.println(ite.next());
??? }
?? }
}

?

?

?

?

?

方法2、

?

public static void main(String[] args){
??String s="anadd";
??char[]arr=s.toCharArray();
?
??Map map=new TreeMap();?
??int max=1;
??List<Character> maxs=new ArrayList<Character>();
??for(int i=0;i<arr.length;i++){
???Integer value=(Integer) map.get(arr[i]);
???if(value==null||value.equals("")||value.intValue()==0){
????map.put(arr[i], 1);
???}else{
????map.put(arr[i], (Integer)map.get(arr[i])+1);
????if(max<(Integer)map.get(arr[i])){
?????max=(Integer)map.get(arr[i]);
?????maxs.removeAll(maxs);
?????maxs.add(arr[i]);
????}else if(max==(Integer)map.get(arr[i])){
?????maxs.add(arr[i]);
????}
??
???}
??}
??
??for(Character s1:maxs){
???System.out.println(s1);
??}
??
?}

}

?

读书人网 >编程

热点推荐