String Permutation

Given two strings, write a method to decide if one is a permutation of the other.

Example

Example 1:
	Input:  "abcd", "bcad"
	Output:  True


Example 2:
	Input: "aac", "abc"
	Output:  False

思路:count比较一下就可以;

public class Solution {
    /**
     * @param A: a string
     * @param B: a string
     * @return: a boolean
     */
    public boolean Permutation(String A, String B) {
        if(A == null && B == null) return true;
        if(A == null || B == null) return false;
        if(A.length() != B.length()) return false;
        
        HashMap<Character, Integer> mapa = new HashMap<Character, Integer>();
        for(int i = 0; i < A.length(); i++){
            char c = A.charAt(i);
            if(mapa.containsKey(c)){
                mapa.put(c, mapa.get(c) +1);
            } else {
                mapa.put(c, 1);
            }
        }
        
        for(int i = 0; i < B.length(); i++){
            char c = B.charAt(i);
            if(!mapa.containsKey(c)){
                return false;
            } else {
                mapa.put(c, mapa.get(c)-1);
                if(mapa.get(c) < 0){
                    return false;
                }
            }
        }
        
        return true;
    }
}
发布了562 篇原创文章 · 获赞 13 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/103760324