Leetcode Longest Common Prefix Solution.
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.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
consists of only lower-case English letters.
Python3 Solution:
class Solution:
def longestCommonPrefix(self, strs):
strs=sorted(strs,key=len)
# here we'll take word having min. length
# because it will have all possible common prefix
# eg. out="flow"
out=strs[0]
# we'll take remaining words in seperate list
li=strs[1:]
pre=''
for i in range(len(out)):
# delare a counter
ct=0
# here we'll take prefix as i.e temp :
# eg. i=0 i=1 i=2 ...so on..
# temp="f" temp="fl" temp="flo"
temp=out[0:i+1]
# here we'll check this temp if matching with other suffixes or not
for j in li:
if temp==j[0:i+1]:
# if matches then increase counter
ct+=1
# if our prefix(temp) matches to all prefix of word in li
# then counter(ct) wil be of length of that li
if ct==len(li):
# here we'll update our prefix eith temp
pre=temp
return pre
ob=Solution()
res=ob.longestCommonPrefix(["flower","flow","flight"])
print(res)
*Note: Constraints are not considered.
Comments
Post a Comment