面试题 01.02. 判定是否互为字符重排

public boolean CheckPermutation(String s1, String s2) {
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        int n = c1.length;
        if(n!=c2.length) return false;
        Map<Character,Integer> map1 = new HashMap<>();
        Map<Character,Integer> map2 = new HashMap<>();
        for(int i = 0;i<n;i++){
            if(!map1.containsKey(c1[i])){
                map1.put(c1[i],1);
            }else{
                map1.put(c1[i],map1.get(c1[i])+1);
            }
            if(!map2.containsKey(c2[i])){
                map2.put(c2[i],1);
            }else{
                map2.put(c2[i],map2.get(c2[i])+1);
            }
        }
        for(char c : c1){
            if(!map2.containsKey(c)) return false;
            if(!map1.get(c).equals(map2.get(c))) return false;
        }
        return true;
    }

 

posted @ 2020-08-22 11:26  欣姐姐  阅读(171)  评论(0编辑  收藏  举报