Leetcode初学——制造字母异位词的最小步骤数(第175周赛)

题目:

分析:

这道题我使用了HashMap进行处理

先将每个字符串按字符存入map中

再比较两个map中的value 的区别

代码:

class Solution {
    public int minSteps(String s, String t) {
        Map<Character,Integer> map1=new HashMap<Character, Integer>();
        Map<Character,Integer> map2=new HashMap<Character, Integer>();
        //将字符串按字符存入map中
        for(int i=0;i<s.length();i++){
            if(!map1.containsKey(s.charAt(i))){
                map1.put(s.charAt(i),0);
            }
            if(!map2.containsKey(t.charAt(i))){
                map2.put(t.charAt(i),0);
            }
            map1.put(s.charAt(i),map1.get(s.charAt(i))+1);
            map2.put(t.charAt(i),map2.get(t.charAt(i))+1);
        }
        int count=0;
        for(char ch:map1.keySet()){
            //如果map2中不存在map1的该字符,直接将map1中对应的value加上
            if(!map2.containsKey(ch)){
                count+=map1.get(ch);
                continue;
            }
            //只有在map1中的value>map2时才操作,否则会有重复加的情况,会干扰判断
            if(map1.get(ch)>map2.get(ch))
                count+=Math.abs(map1.get(ch)-map2.get(ch));
        }
        return count;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值