#14 Longest Common Prefix
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: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
Solution1:
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
output = ""
next = True
index = 0
# check if empty list
if len(strs) == 0:
return ""
# check if empty string inside list
for i in range(len(strs)):
if len(strs[i]) == 0:
return ""
# compare each letter of each string
while(next):
letter = strs[0][index]
for i in range(len(strs)):
if strs[i][index] != letter:
next = False
break
if next:
output += letter
index += 1
for i in range(len(strs)):
if len(strs[i]) <= index:
next = False
return output
Solution2:
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 0:
return ""
output = ""
index = 0
while True:
letter = ''
for word in strs:
if len(word) == index:
return output
else:
if letter == '':
letter = word[index]
else:
if word[index] != letter:
return output
index += 1
output += letter