Question
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"
Plain Text
복사
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Plain Text
복사
My Answer
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) < 2:
return strs[0]
strs.sort(key= lambda x: len(x))
for i in range(len(strs[0])):
for j in range(1, len(strs)):
if strs[0][i] != strs[j][i]:
return strs[0][:i]
return strs[0]
Python
복사
가장 짧은 str가지고 처음부터
Optimized Version
No Optimization needed
Python
복사