strs은 단어가 담긴 배열입니다. 공통된 시작 단어(prefix)를 반환해주세요.
요구사항 : 여러 string들끼리 공통된 부분을 찾아라
제한사항 : 없음
인풋 : string이 담긴 list
아웃풋 : 하나의 string값.
본질 : string의 index 성질을 이용해서 서로 비교해라
def get_prefix(strs):
if not strs:
return ""
common_str = strs[0]
for string in strs[1:]:
for i,s in enumerate(string):
if i >= len(common_str):
continue
if s != common_str[i]:
common_str = string[:i]
continue
return common_str
짝꿍님이 생각하신 방법. 첫번째와 아이디어는 같았지만, 반복문을 실행하는 순서가 달랐다.
def get_prefix(strs):
if not strs:
return ""
common_str = min(strs, key=len)
result = ""
for i,c in enumerate(common_str):
for string in strs:
if string[i] != c:
return result
result += c
return result
동명(선생)님이 생각하신 방법.
def get_prefix(strs):
min_word = min(strs, key=len) if strs else ''
for i, c in enumerate(min_word):
for word in strs:
if word[i] != c:
return min_word[:i]
return min_word