[LintCode] Compare Strings

422 查看

Problem

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.

Notice

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

Example

For A = "ABCD", B = "ACD", return true.

For A = "ABCD", B = "AABC", return false.

Note

建立一个长度为26的数组,每一位对应那个字母出现的个数,先遍历A,对数组做增操作,再遍历B,对数组做减操作。

Solution

public class Solution {
    public boolean compareStrings(String A, String B) {
        int[] count = new int[26];
        for(int i = 0; i < A.length(); i++){
            count[A.charAt(i) - 'A']++;
        }
        for(int i = 0; i < B.length(); i++){
            count[B.charAt(i) - 'A']--;
            if(count[B.charAt(i) - 'A'] < 0) {
            return false;
            }
        }
        return true;    
    }
}