10. commonCharacterCount


Task

Given two strings, find the number of common characters between them.

Example

For s1 = "aabcc" and s2 = "adcaa", the output should be commonCharacterCount(s1, s2) = 3.

Strings have 3 common characters - 2 “a”s and 1 “c”.

Input/Output

  • [execution time limit]
    4 seconds (py3)

  • [input] string s1
    A string consisting of lowercase English letters.
    Guaranteed constraints: 1 ≤ s1.length < 15.

  • [input] string s2
    A string consisting of lowercase English letters.
    Guaranteed constraints: 1 ≤ s2.length < 15.

  • [output] integer

My Solution

def commonCharacterCount(s1, s2):
    fstCount = {}
    sndCount = {}
    commonCount = 0
    for letter in s1:
        if letter in fstCount:
            fstCount[letter] += 1
        else:
            fstCount[letter] = 1
    for letter in s2:
        if letter in sndCount:
            sndCount[letter] += 1
        else:
            sndCount[letter] = 1
    for key, val in fstCount.items():
        if key in sndCount:
            commonCount += min(val, sndCount[key])
    return commonCount