使用 Java 查找字符串中出現次數最多的字符以及出現的次數?


使用 Java 查找字符串中出現次數最多的字符以及出現的次數?

import java.util.HashMap;
import java.util.Map;

public class TestStringSum {
	public static void main(String[] args) {
		String str = "abcdefgaaabbb";
		int max = 0;
		Map<Character, Integer> map = new HashMap<Character, Integer>(str.length());
		for (char c : str.toCharArray()) {
			Integer i = map.get(c);
			int value = (i == null) ? 0 : i;
			map.put(c, ++value);
			max = value > max ? value : max;
		}
		for (Character key : map.keySet()) {
			if (map.get(key) == max) {
				System.out.println("most frequent Character => " + key + ", Count => " + max);
			}
		}
	}
}

點擊查看結果

``` most frequent Character => a, Count => 4 most frequent Character => b, Count => 4 ```

參考鏈接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM