[leetcode] 14. Longest Common Prefix
2021. 8. 10. 15:27ㆍ노트/Algorithm : 알고리즘
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.
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
li = []
for string in strs:
li.append(len(string))
min_l = min(li)
res = []
i = 0
while i < min_l:
filter_string = [string[i] for string in strs]
if len(set(filter_string)) == 1:
res.append(filter_string[0])
else:
break
i+=1
return ''.join(res)
'노트 > Algorithm : 알고리즘' 카테고리의 다른 글
[leetcode] 21. Merge Two Sorted Lists (0) | 2021.08.10 |
---|---|
[leetcode] 20. Valid Parentheses (0) | 2021.08.10 |
[leetcode] 13. Roman to Integer (0) | 2021.08.06 |
[leetcode] 1. Two Sum (0) | 2021.08.06 |
[leetcode] 2. Add Two Numbers (0) | 2021.08.03 |