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;
        }
    }
}
全部评论

相关推荐

宇算唯航:目测实缴资本不超100W的小公司
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 12:11
点赞 评论 收藏
分享
06-25 16:25
梧州学院 Java
愿汐_:项目介绍那么长,然而你做了啥就一句话?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务