求一个z字符串中出现次数最多的那个字母及次数,如有多个重复则一起求出
public class ArrayChar {
@Test
public void demo1(){
String input ="aavzadfdsgfsdhshgwasdfasdfdddaaa";
doString(input);
}
public void doString(String input){
char[] chars = input.toCharArray();
/* for (char c:chars) {
System.out.println(c);
}*/
ArrayList list = new ArrayList();
TreeSet set = new TreeSet();//去除重复的字母
for(int i =0;i<chars.length;i++){
list.add(String.valueOf(chars[i]));
set.add(String.valueOf(chars[i]));
}
System.out.println(set);
Collections.sort(list);
System.out.println(list);
Iterator iterator = set.iterator();
int max = 0;
int first,last,length;
String maxChar = null;
while(iterator.hasNext()){
String key = (String) iterator.next();
first = list.indexOf(key);
last = list.lastIndexOf(key);
length = last - first + 1;
if(length>max){
max = length;
maxChar = key;
}
else if (length == max){
maxChar = maxChar+" "+key;
}
}
System.out.println(max+" "+maxChar);
}
}
输出:
[a, d, f, g, h, s, v, w, z]
[a, a, a, a, a, a, a, a, d, d, d, d, d, d, d, d, f, f, f, f, g, g, h, h, s, s, s, s, s, v, w, z]
8 a d