Compare Strings

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.

分析:

用array记录每个字符在A中出现的个数,然后再减去B中的字符,如果不够,说明不包含。

 1 public class Solution {
 2     /**
 3      * @param A : A string includes Upper Case letters
 4      * @param B : A string includes Upper Case letter
 5      * @return :  if string A contains all of the characters in B return true else return false
 6      */
 7     public boolean compareStrings(String A, String B) {
 8         if (A == null & B != null) return false;
 9         if (A == null && B == null) return true;
10         if (B == null) return true;
11         
12         int[] charCounts = new int[256];
13         
14         for (int i = 0; i < A.length(); i++) {
15             charCounts[A.charAt(i)]++;
16         }
17         
18         for (int i = 0; i < B.length(); i++) {
19             if (charCounts[B.charAt(i)] == 0) {
20                 return false;
21             }
22             charCounts[B.charAt(i)]--;
23         }
24         return true;
25     }
26 }

 

posted @ 2016-07-06 12:17  北叶青藤  阅读(171)  评论(0)    收藏  举报