【一次过】【HashMap】Lintcode 211. 字符串置换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/82682561

给定两个字符串,请设计一个方法来判定其中一个字符串是否为另一个字符串的置换。

置换的意思是,通过改变顺序可以使得两个字符串相等。

样例

"abc" 为 "cba" 的置换。

"aabc" 不是 "abcc" 的置换。


解题思路:

将字符串A放入哈希表中,key为字符,value为该字符出现的次数。然后依次扫描B,更新哈希表次数。最后哈希表中的value值都为0时代表B与A互为变形词。

public class Solution {
    /**
     * @param A: a string
     * @param B: a string
     * @return: a boolean
     */
    public boolean Permutation(String A, String B) {
        // write your code here
        if(A.length()==0 && B.length()==0)
            return true;
        if(A.length()==0 || B.length()==0)
            return false;
        if(A.length() != B.length())
            return false;
        
        Map<Character,Integer> map = new HashMap<>();
        for(int i=0 ; i<A.length() ; i++)
            map.merge(A.charAt(i), 1, Integer::sum);
        
        
        for(int i=0 ; i<B.length() ; i++){
            if(map.get(B.charAt(i))!=null && map.get(B.charAt(i))>0){
                map.put(B.charAt(i) , map.get(B.charAt(i))-1);
            }else{
                return false;
            }
        }
        
        for(Character word : map.keySet()){
            if(map.get(word) != 0)
                return false;
        }
        
        return true;
    }
}

像这样字符串中的的字符都是ASCII码,可以使用数组来代替HashMap,方便快捷。

public class Solution {
    /**
     * @param A: a string
     * @param B: a string
     * @return: a boolean
     */
    public boolean Permutation(String A, String B) {
        // write your code here
        if(A.length()==0 && B.length()==0)
            return true;
        if(A.length()==0 || B.length()==0)
            return false;
        if(A.length() != B.length())
            return false;
        
        int[] map = new int[256];
        for(int i=0 ; i<A.length() ; i++)
            map[A.charAt(i)]++;
        
        
        for(int i=0 ; i<B.length() ; i++){
            if(map[B.charAt(i)] == 0)
                return false;
            else
                map[B.charAt(i)]--;
        }
        
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/82682561