Created
February 1, 2022 07:10
-
-
Save tanmay27vats/6abf35f31e2ca726503371b35ae6aad8 to your computer and use it in GitHub Desktop.
[Python] 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: strs = ["flower","flow","flight"] Output: "fl" Example 2: Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def longestCommonPrefix(self, strs: List[str]) -> str: | |
if len(strs) == 0: | |
return "" | |
common_prefix = strs[0] | |
for i in range(1,len(strs)): | |
temp = "" | |
if len(common_prefix) == 0: | |
break | |
for j in range(len(strs[i])): | |
if j<len(common_prefix) and common_prefix[j] == strs[i][j]: | |
temp+=common_prefix[j] | |
else: | |
break | |
common_prefix = temp | |
return common_prefix |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment