要求:需要对一个字符串中字符出现次数进行统计,这里分别使用顺序存储和散列映射存储两种方式统计字符出现次数
散列映射存储(HashMap)
1 2 3 4 5 6 7 8 9 10 11
| public static HashMap<String, Integer> statisticStrCountMap(String str) { HashMap<String, Integer> map = new HashMap<>(); for (int i = 0; i < str.length(); i++) { String c = str.substring(i, i + 1); Integer value = map.get(c); int count = value != null ? value : 0; map.put(c, ++count); } return map; }
|
顺序存储(ArrayList)
查找效率低不推荐使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
public static List<String> statisticStrCount(String str) { ArrayList<String> list = new ArrayList<>(); for (int i = 0; i < str.length(); i++) { String c = str.substring(i, i + 1); int index = -1; for (int j = 0; j < list.size(); j++) { if (list.get(j).substring(0,1).equals(c)) { index = j; break; } } if (index > -1) { int number = Integer.parseInt(list.get(index).split("->")[1]) + 1; list.set(index, c + "->" + number); } else { list.add(c + "->1"); } } return list; }
|