一个字符串中可能包含a~z中的多个字符,如有重复,如String data="aavzcadfdsfsdhshgWasdfasdf",
求出现次数最多的那个字母及次数,如有多个重复的则都求出。〔金山公司面试题〕
实现代码如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.TreeSet;
public class FindRepeatChar {
public static void doString(String strInput) {
char[] chars = strInput.toCharArray();
ArrayList lists = new ArrayList();
TreeSet set = new TreeSet(); //
for (int i = 0; i < chars.length; i++) {
lists.add(String.valueOf(chars[i]));
set.add(String.valueOf(chars[i])); //引入TreeSet,通过集合快速找到 出现的 字符串
}
System.out.println(set);
Collections.sort(lists); //引入ArrayList,实现快速排序
System.out.println(lists);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < lists.size(); i++) {
sb.append(lists.get(i)); //通过StringBuffer生成排序后的字符串
}
strInput = sb.toString();
System.out.println(strInput);
int max = 0;
String maxString = "";
ArrayList maxList = new ArrayList();
for (Iterator its = set.iterator(); its.hasNext();) {
String os = (String) its.next();
int begin = strInput.indexOf(os); //每个字符第一次出现的位置
int end = strInput.lastIndexOf(os); //每个字符最后一次出现的位置
int value = end - begin + 1;
if (value > max && value > 1) {
maxList.clear(); //应该加上这条语句
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("出现最多的字符为:");
for (int i = 0; i < maxList.size(); i++) {
System.out.println(maxList.get(i) + "");
}
System.out.println();
System.out.println("出现最多的次数为:" + max);
}
public static void main(String[] args) {
String strInput = new String("aavzcadfdsfsdhshgWasdfasdf");//网上给的代码加个"W",就不能满足需求了
doString(strInput);
}
}