문제/릿코드
[릿코드/LeetCode] 14. Longest Common Prefix (파이썬3/Python3)
개 살구
2021. 7. 10. 23:08
문제
https://leetcode.com/problems/longest-common-prefix/
Longest Common Prefix - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
생각
prefix면 앞에서부터 비교해야하는 건가?
우선 list안에 있는 가장 짧은 단어를 찾고
이를 기준으로 앞에서부터 비교?
-
파이썬 문자열 길이를 기준으로 정렬하려면, sort 메소드에서 key=len을 하면 된다고 함!
코드
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 1:
return (strs[0])
strs.sort(key=len)
result = ""
for i in range(len(strs[0])):
find = strs[0][i]
for j in range(1,len(strs)):
if find == strs[j][i]:
if j == len(strs)-1:
result += find
continue;
return result
return result
생각과 다르게 이중 for문을 쓰게 되어서 아쉽다는 생각을 함.
생각지도 못한 경우의 수가 있어서 조금 헤맸음