查找字符串中相同的最大字符和个数

来源:互联网 发布:天津商业大学网络登录 编辑:程序博客网 时间:2024/05/16 08:48
/**
* 查找字符串中相同最多的字符个数和字符
* @param str
*/
public static void findMaxCountChars(String str) {
long time = System.currentTimeMillis();
if (str == null || str.length() == 0) {
return;
}
int length = str.length();
List<Character> charList = new ArrayList<Character>(length);
for (int i = 0; i < length; i++) {
charList.add(str.charAt(i));
}
Collections.sort(charList);
int max = 0;
char ch = charList.get(0);
StringBuffer sb = new StringBuffer(10);
sb.append(ch);
int index = 0;
int listSize = charList.size();
while (index < listSize && ch == charList.get(index++))
max++;


int pmax = 0;
while (index < listSize) {
index--;
ch = charList.get(index);
while (index < listSize && ch == charList.get(index++))
pmax++;
if (pmax > max) {
max = pmax;
sb.delete(0, sb.length());
sb.append(ch);
} else if (pmax == max) {
sb.append(ch);
}
pmax = 0;
}


if (max == 1) {
sb.append(charList.get(index - 1));
}


System.out.println("max char:" + sb.toString() + ",count:" + max
+ ",time:" + (System.currentTimeMillis() - time));


}
0 0
原创粉丝点击