https://leetcode.com/problems/longest-common-prefix/description/
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 ""
.
Input: ["flower","flow","flight"] Output: "fl"
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Easy question.
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
if len(strs) == 1:
return strs[0]
prefix = ""
i = 0
while True:
if i > len(strs[0]) - 1:
return prefix
char = strs[0][i]
for str in strs[1:]:
if i > len(str) - 1:
return prefix
if str[i] != char:
return prefix
prefix += char
i += 1
return prefix