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.


一个Hashtable的题,用Hashtable统计A中各个字符出现的次数,当B中出现的时候就减去相应的次数,如果次数为负,说明B中出现了A中没有的字符

1
2
3
4
5
6
7
8
9
10
11
12
13
public boolean compareStrings(String A, String B) {
int[] chars = new int[26];
for (int i = 0; i < A.length(); i++) {
chars[A.charAt(i) - 'A']++;
}
for (int i = 0; i < B.length(); i++) {
chars[B.charAt(i) - 'A']--;
if (chars[B.charAt(i) - 'A'] < 0)
return false;
}
return true;
}