Computer Science/알고리즘 문제풀이

[codesignal][python] 8. commonCharacterCount

codesignal.com

 

Coding Tests and Assessments for Technical Hiring | CodeSignal

Learn how you can go beyond resumes in technical hiring with a state-of-the-art assessment platform and advanced coding tests

codesignal.com

level : easy

Question:

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

두 string이 주어지면 서로 같은 겹치는 요소의 개수를 반환하는 문제

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".

 


def commonCharacterCount(s1, s2):
    alphabet_set=set(s1)
    solution=0
    for i in alphabet_set:
        print(i)
        solution+=min(s1.count(i),s2.count(i))
    return solution

My answer:

  • 일단 한 string에 어떤 문자들이 있는지 set()을 통해 구한다. -> alphabet_set
  • 그리고 각 문자열에 alphabet_set의 요소들이 몇개씩 있는지 구한 후, 겹치는 만큼을 구해야 하기 때문에 min을 취해준다.
  • 모든 alphabet_set에 있는 요소들에 대해서 summation