卖萌的弱渣

I am stupid, I am hungry.

Compare Strings

Compare Strings

Example

For A = “ABCD”, B = “ACD”, return true.

For A = “ABCD”, B = “AABC”, return false.

Note

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

Solution

  • Array characters[256] record all possible letters. Initialize it as all zeros
  • Scan the array A and characters[A[i]-‘A’]++
  • Scan the array B, characters[B[i]-‘A’]–. If find any characters[B[i]-‘A’] <= 0. Then Array A cannot have this character of Array B.
(Compare-Strings.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    """
    @param A : A string includes Upper Case letters
    @param B : A string includes Upper Case letters
    @return :  if string A contains all of the characters in B return True else return False
    """
    def compareStrings(self, A, B):
        # write your code here
        # an array to carry all characters
        characters = [0] * 256

        for i in range(len(A)) :
            index = ord(A[i]) - ord('A')
            characters[index] += 1

        for i in range(len(B)) :
            index = ord(B[i]) - ord('A')
            if characters[index] == 0:
                return False
            characters[index] -= 1

        return True