1. 程式人生 > >java怎麽實現統計一個字符串中字符出現的次數

java怎麽實現統計一個字符串中字符出現的次數

com () contains 源碼 返回 key 保護 entryset title

問題:假設字符串僅僅保護a-z 的字母,java怎麽實現統計一個字符串中字符出現的次數?而且,如果壓縮後的字符數不小於原始字符數,則返回。

處理邏輯:首先拆分字符串,以拆分出的字符為key,以字符出現次數為value,存入Map中。

源碼如下:

 1 import java.util.HashMap;
 2 import java.util.Iterator;
 3 import java.util.Map;
 4 
 5 public class TestCompress {
 6     
 7     public static void main(String[] args) {
 8
String str = "aaabbbcccdfb"; 9 compress(str); 10 } 11 12 public static void compress(String str) { 13 Map<String, Integer> count = new HashMap<String, Integer>(); 14 String[] myStrs = str.split(""); 15 for (int i = 0; i < myStrs.length; i++) {
16 int totalNum = 1; 17 String currentStr = myStrs[i]; 18 if (count.containsKey(currentStr)) { 19 totalNum = count.get(currentStr) + 1; 20 } 21 count.put(currentStr, totalNum); 22 } 23 int num = count.size();
24 System.out.println("壓縮結果"); 25 if (num == myStrs.length) { 26 System.out.println("各個字母都不一樣,直接返回"); 27 System.out.println(str); 28 return; 29 } 30 String result = ""; 31 Iterator<Map.Entry<String, Integer>> it = count.entrySet().iterator(); 32 while (it.hasNext()) { 33 Map.Entry<String, Integer> entry = it.next(); 34 result = result + entry.getKey() + entry.getValue(); 35 } 36 System.out.println(result); 37 } 38 }

運行結果:

1 壓縮結果
2 a3b4c3d1f1

java怎麽實現統計一個字符串中字符出現的次數