| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 코복장
- 딥러닝
- 부분수열의 합2
- 정답코드
- 다이나믹 프로그래밍
- 실질적 약수
- dfs
- 구현
- C
- dp
- 코딩테스트
- 스펨메일 분류
- populating next right pointers in each node
- 2247
- T tree
- 27448
- 샤논 엔트로피
- 모두의 꿈
- 아니메컵
- lgb
- 백준
- 코테
- 정렬
- 파이썬
- BFS
- 코딩
- python
- 힙 정렬
- ps
- 17070
Archives
- Today
- Total
코딩복습장
LeetCode: Longest Common Prefix 본문
728x90
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lowercase English letters if it is non-empty.
생각보다 어려운 문제이다.
모든 단어의 공통된 문자열을 반환해야하는 문제인데, 막상 풀려고 하면 논리를 세우기 힘들다.
풀이과정은 다음과 같다.
1. 첫 단어를 prefix로 정한다.
2. 두 번째 단어부터 비교하여 공통된 문자열로 시작하는지 확인한다.
3. 아니라면 prefix를 한칸 줄인다.
2, 3을 반복하면 문제가 풀린다.

구현코드
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
prefix = strs[0] # 첫 단어 기준으로 시작
for word in strs[1:]:
while not word.startswith(prefix):
prefix = prefix[:-1] # 접두사를 줄여가며 비교
if prefix == "":
return ""
return prefix728x90
'코딩 테스트 > python(파이썬)' 카테고리의 다른 글
| LeetCode: Remove Element (2) | 2025.06.07 |
|---|---|
| 백준: 14891번 톱니바퀴 (0) | 2025.06.06 |
| LeetCode: Valid Parentheses (0) | 2025.06.03 |
| LeetCode: Maximum Gap (0) | 2025.05.31 |
| 백준: 구슬 탈출 2 (13460번) (2) | 2025.05.30 |
Comments