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.
func longestCommonPrefix(strs []string) string {
if len(strs) == 0 {
return ""
}
var prefix string = strs[0]
for _, str := range strs {
var curr string = ""
var IsUpdated bool = false
for j := range str {
curr = string(str[0:j+1])
if !strings.HasPrefix(prefix, curr) {
prefix = string(curr[0:j])
IsUpdated = true
break
}
}
if !IsUpdated {
prefix = curr
}
}
return prefix
}
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
prefix = strs[0]
for inner in strs:
curr = ""
updated = False
for i in range(0, len(inner)):
curr = str(inner[0: i+1])
if not(prefix[0: i+1] == curr):
prefix = curr[0: i]
updated = True
break
if not(updated):
prefix = curr[0: len(curr)]
return prefix