Checking if two strings are permutations of each other

前端 未结 30 935
感情败类
感情败类 2020-12-05 08:19

How to determine if two strings are permutations of each other

30条回答
  •  有刺的猬
    2020-12-05 08:54

    public boolean isPermutationOfOther(String str, String other){
        if(str == null || other == null)
            return false;
        if(str.length() != other.length())
            return false;
    
        Map characterCount = new HashMap();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int count = 1;
            if(characterCount.containsKey(c)){
                int k = characterCount.get(c);
                count = count+k;
            }
    
            characterCount.put(c, count);
    
        }
    
        for (int i = 0; i < other.length(); i++) {
            char c = other.charAt(i);
            if(!characterCount.containsKey(c)){
                return false;
            }
    
            int count = characterCount.get(c);
            if(count == 1){
                characterCount.remove(c);
            }else{
                characterCount.put(c, --count);
            }
        }
    
        return characterCount.isEmpty();
    }
    

提交回复
热议问题