统计字符串中出现次数最多的字母的次数,如果有多个重复的,都求出
package javastudy; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.TreeSet; public class Test1 { public static void main(String [] args){ String str = "aacdggdhrdhgsjrsovoiwimtcpiq"; new Test1().doString(str) ; } public void doString (String str){ char [] chars = str.toCharArray() ; ArrayList<String> lists = new ArrayList<String>() ; TreeSet<String> set = new TreeSet<String>(); for (int i=0;i<chars.length;i++){ lists.add(String.valueOf(chars[i])); set.add(String.valueOf(chars[i])); } //有序且无重复,找到所有出现的 System.out.println("set:"+set); //有序可以有重复,arraylist可以快速排序 Collections.sort(lists) ; System.out.println("lists:"+lists) ; //得到排序后的字符串 StringBuffer sb = new StringBuffer() ; for (int i=0;i<lists.size();i++){ sb.append(lists.get(i)) ; } str = sb.toString(); System.out.println("str after sorted:"+str) ; //统计了第一个出现最多的char的次数 ,记下出现最多的次数 为max,对应的char为maxString int max =0; String maxString =""; ArrayList<String> maxList = new ArrayList<String>(); Iterator itr = set.iterator() ; while (itr.hasNext()) { String os= (String)itr.next() ; int begin = str.indexOf(os) ; int end = str.lastIndexOf(os) ; int value = end-begin+1; if (value>max){ max= value ; maxString = os ; maxList.add(os) ; }else if (value == max) { maxList.add(os); } } //找到最大的位置 int index = 0; for (int i=0;i<maxList.size();i++){ if (maxList.get(i).equals(maxString)){ index =i; break ; } } System.out.println("max data"); for (int i=index;i<maxList.size();i++){ System.out.println(maxList.get(i)+""); } System.out.println() ; System.out.println("max:"+ max) ; } }
输出结果为
set:[a, c, d, g, h, i, j, m, o, p, q, r, s, t, v, w]
lists:[a, a, c, c, d, d, d, g, g, g, h, h, i, i, i, j, m, o, o, p, q, r, r, s, s, t, v, w]
str after sorted:aaccdddggghhiiijmoopqrrsstvw
max data
d
g
i