java语言实现:找出字符串中出现次数最多的字母(最多的字母只有一个)例如输入: aaabbbbbbbbbbcccd 输出为: 出现最多的字母是 b 出现最多的字母的次数是:10

利用java语言实现:找出字符串中出现次数最多的字母(最多的字母只有一个)例如输入:

aaabbbbbbbbbbcccd

输出为:

出现最多的字母是  b
出现最多的字母的次数是:10



package 字符串;

import java.util.ArrayList;
import java.util.List;

public class RepeatWordNum {
	public static void main(String[] args) {
		String str1 = "aaabbbbbbbbbbcccd";

		int Num=RepeatWordNum.findRepeatWordNum(str1);
		System.out.println("出现最多的字母的次数是:"+Num);
	}

	public static int findRepeatWordNum(String str) {
		char[] ch1 = str.toCharArray();
		List<Character> list = new ArrayList<Character>();
		for (int i = 0; i < ch1.length; i++) {
			list.add(ch1[i]);
		}
		int maxNum = 1;
		int maxIndex = 0;
		List<Integer> list2 = new ArrayList<Integer>();
		for (int j = 0; j < list.size(); j++) {
			int count = 1;
			int n = 0;
			for (n = j + 1; n < list.size(); n++) {

				if (list.get(j) == list.get(n)) {
					count++;
					list.remove(n);
					n--;
				}
			}
			if (maxNum < count) {
				maxNum = count;
				maxIndex = j;
			}
		}
		System.out.println("出现最多的字母是  "+list.get(maxIndex));
		return maxNum;
	}
}

控制台打印:


猜你喜欢

转载自blog.csdn.net/handsome2013/article/details/80505873