问题:假设字符串仅仅保护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