java一个字符串中出现次数最多的字符以及次数

最多的字符和它出现的次数

public class Zifuchuan {
public String s="aabblkwefikksjdjfjejkkkkkkkkkkkkac";
public char a; //对比字母
public char b; //被对比字母
public char c; //出现次数最多的字母
public int al=0; //对比字母的长度
public int zl=0; //保留对比字母最大数
public int sl=0; //字符串长度
public void chakan(){
sl=s.length();
for(int i=0;i<sl;i++){
a= s.charAt(i);
for(int j=0;j<sl;j++){
b=s.charAt(j);
if(a==b){
al++;
}
}
if(al>zl){
zl=al;
c=a;
}
al=0;
}
System.out.println("al="+al+"出现字母最多次数为"+zl+"出现次数作最多的字母是"+c);
}
public static void main(String[] args) {
Zifuchuan z= new Zifuchuan();
z.chakan();
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-04-27
public class StringTimes {

/**
*
*/
public StringTimes() {
// TODO Auto-generated constructor stub
}

public void method(String s){
Map map = new HashMap();
for (int i = 0 ;i < s.length();i++){
Character c = new Character(s.charAt(i));
Integer count =(Integer) map.get(c);
if (count==null){
map.put(c, 1);
}else{
map.put(c, count+1);
}
}
Iterator iter = map.entrySet().iterator();
int max = 0;
char ch = ' ';
while(iter.hasNext()){
Map.Entry entry = (Entry) iter.next();
if((Integer)entry.getValue()>max){
max = (Integer) entry.getValue();
ch = (Character)entry.getKey();
}
}
System.out.println("最多的字符是:"+ch);
System.out.println("出现的次数是:"+max);
}

public static void main(String[] args){
StringTimes st = new StringTimes();
st.method("bbcccceeddkkkll");
}
}
第2个回答  2010-04-27
我以前面试过一个这样的题,给你一个参考吧.
package com.dyc.difficult;

import java.util.*;

public class FindMostEle {
private static HashMap<String, Integer> map;

public static HashMap<String, Integer> mostEle(String[] strArray) {
map = new HashMap<String, Integer>();
String str = "";
int count = 0;
int result = 0;
for (int i = 0; i < strArray.length; i++)
str += strArray[i];
for (int i = 0; i < strArray.length; i++) {
String temp = str.replaceAll(strArray[i], "");
count = (str.length() - temp.length()) / strArray[i].length();
if (count > result) {
map.clear();
map.put(strArray[i], count);
result = count;
} else if (count == result)
map.put(strArray[i], count);
}
return map;
}

public static void main(String args[]) {
String[] strArray = { "11", "11", "2", "2", "4", "5", "4" };
HashMap<String, Integer> result = mostEle(strArray);
ArrayList<Integer> c = new ArrayList<Integer>(result.values());
Set<String> s = result.keySet();
System.out.print("一共有" + result.size() + "元素最多。它们分别是");
System.out.print(s);
System.out.println(",分别出现了" + c.get(0) + "次。");
}
}
第3个回答  2010-04-27
public static void main(String[] args) {
test("abbcccddddaa");
}
public static void test(String str) {
int max_length = 0;
String max_str = "";
while (str.length() > 0) {
int length = str.length();
String first = str.substring(0, 1);
str = str.replaceAll(first, "");
if (max_length < length - str.length()) {
max_length = length - str.length();
max_str = first;
}
}
System.out.println(max_length);
System.out.println(max_str);
}

你可以参考下:
http://xiaojianhx.javaeye.com/admin/blogs/491147
我的javaeye博客本回答被提问者采纳
相似回答