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;
    }
}
发布了57 篇原创文章 · 获赞 3 · 访问量 1059

猜你喜欢

转载自blog.csdn.net/qq_39377543/article/details/104232401