LARGEST COMMON PREFIX

14. Longest Common Prefix
Easy
12.7K
3.8K
Companies

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.
My_CODE:
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: a="" for i in range(len(strs[0])): b=strs[0][i] for j in range(1,len(strs)):
#try-except:if next letter index is not present in next string eg['ab',a'] try: if b!=strs[j][i]: return a except IndexError: return a a+=b return a

OTHER CODE:
(1)
def longestCommonPrefix(self, strs): prefix="" if len(strs)==0: return prefix for i in range(len(min(strs))): c=strs[0][i] if all(a[i]==c for a in strs): prefix+=c else: break return prefix


Comments

Popular posts from this blog