Common Characters

Tiffany ·2024년 3월 5일
0

AlgoExpert

목록 보기
3/20

주어진 모든 문자열이 갖는 공통된 문자를 찾고 리스트로 리턴 하는 함수 구현 문제이다.
이문제를 처음 봤을때 어떤 단어를 기준으로 하여 루프를 돌려야 하나 고민했지만, 사실 아무 단어를 기준으로 하여도 상관이 없다 제목을 보면 왜인지 알 수 있다. 공통된 문자를 찾는 문제이기 때문에.

["abc", "bcd", "cbad"]
["b", "c"] 

def commonCharacters(strings):
    result = [] 
    
    for letter in strings[0]:
        count = 0 
        for string in strings:
            if letter in string: 
                count += 1 
        if count == len(strings):
            result.append(letter)        
    return set(result) 

제일 짧은 단어를 기준으로 하면 러닝타임이 단축이 될 수는 있을것같지만 어짜피 함수로 표현하면 M * N where M is the length of the picked string and M is the number of the elements in the given array.

profile
Love what you do and don't quit.

0개의 댓글