Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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.
My code:
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs)==0:
return ""
final_str=""
j=0
length=10000000
for i in range(len(strs)):
if length>len(strs[i]):
length=len(strs[i])
while j<length:
flag=True
for i in range(len(strs)):
tmp_str=strs[i]
if j>=len(strs[i]):
break
if i==0:
check_str=tmp_str[j]
continue
if check_str!=tmp_str[j]:
flag=False
if flag==True:
final_str=final_str+tmp_str[j]
else:
break
j=j+1
return final_str
Solution:
https://leetcode.com/problems/longest-common-prefix/