HashMap 解决计算字符个数问题
计算字符个数
http://www.nowcoder.com/questionTerminal/a35ce98431874e3a820dbe4b2d0508b1
用了hashmap来做。当然还是推荐(str.length()-str.replaceAll(s,"").length()
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String input = sc.next(); String upperStr = input.toUpperCase(); char c = sc.next().toUpperCase().charAt(0); int ans = checkNum(upperStr, c); System.out.print(ans); } private static int checkNum(String str, char c){ int res = 0; int len = str.length(); HashMap<Character, Integer> map= new HashMap<> (); for(int i = 0; i < len; i++){ char cur = str.charAt(i); map.put(cur, map.getOrDefault(cur, 0)+1); } if(!map.containsKey(c)){ return res; } else { res = map.get(c); return res; } } }