55 · Compare Strings - LintCode

# Description

Compare two strings A and B , determine whether A contains all of the characters in B .

The characters in string A and B are all Upper Case letters.

The characters of B in A are not necessary continuous or ordered.

# Example

Example 1:

Input:

A = "ABCD"
B = "ACD"

Output:

true

Explanation:

A contains all the characters in B.

Example 2:

Input:

A = "ABCD"
B = "AABC"

Output:

false

Explanation:

A does not contain all the characters in B.

# Code

可以用 hashMap

public class Solution {
    /**
     * @param A: A string
     * @param B: A string
     * @return: if string A contains all of the characters in B return true else return false
     */
    public boolean compareStrings(String A, String B) {
        if (B == null) return true;
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < B.length(); i++) {
            map.put(B.charAt(i), map.getOrDefault(B.charAt(i), 0) + 1);
        }
        
        for (int i = 0; i < A.length(); i++) {
            if (map.containsKey(A.charAt(i))) {
                 map.put(A.charAt(i), map.get(A.charAt(i)) - 1);
                 if (map.get(A.charAt(i)) == 0) {
                     map.remove(A.charAt(i));
                 }
            }
        }
        
        if (map.isEmpty()) return true;
        return false;
    }
}