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.
思路
题目里讲所有字符都是大写的。那么我们就想到只需要开一个长为26的数组来进行记录。
第一遍过A的时候往上加。第二遍过B的时候往下减。
当数组里的数字check[i] < 0时,说明这个字符在B里出现的次数比在A里出现的次数多。那么就是false了。
Code
public class Solution { /** * @param A : A string includes Upper Case letters * @param B : A string includes Upper Case letter * @return : if string A contains all of the characters in B return true else return false */ public boolean compareStrings(String A, String B) { // write your code here int[] check = new int[26]; for (int i = 0; i < A.length(); i++) { check[A.charAt(i) - 'A']++; } for (int i = 0; i < B.length(); i++) { if (--check[B.charAt(i) - 'A'] < 0) { return false; } } return true; } }