You are given an array of strings strs. Return the longest common prefix of all the strings.
If there is no longest common prefix, return an empty string "".
Example 1:
Input: strs = ["bat","bag","bank","band"]
Output: "ba"Example 2:
Input: strs = ["dance","dag","danger","damage"]
Output: "da"Example 3:
Input: strs = ["neet","feet"]
Output: ""Constraints:
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i] is made up of lowercase English letters if it is non-empty.class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
prefix = strs[0]
for i in range(1, len(strs)):
j = 0
while j < min(len(prefix), len(strs[i])):
if prefix[j] != strs[i][j]:
break
j += 1
prefix = prefix[:j]
return prefixWhere is the length of the shortest string and is the number of strings.
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
for i in range(len(strs[0])):
for s in strs:
if i == len(s) or s[i] != strs[0][i]:
return s[:i]
return strs[0]Where is the length of the shortest string and is the number of strings.
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 1:
return strs[0]
strs = sorted(strs)
for i in range(min(len(strs[0]), len(strs[-1]))):
if strs[0][i] != strs[-1][i]:
return strs[0][:i]
return strs[0]Where is the length of the longest string and is the number of strings.
class TrieNode:
def __init__(self):
self.children = {}
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
def lcp(self, word: str, prefixLen: int) -> int:
node = self.root
for i in range(min(len(word), prefixLen)):
if word[i] not in node.children:
return i
node = node.children[word[i]]
return min(len(word), prefixLen)
class Solution:
def longestCommonPrefix(self, strs: list[str]) -> str:
if len(strs) == 1:
return strs[0]
mini = 0
for i in range(1, len(strs)):
if len(strs[mini]) > len(strs[i]):
mini = i
trie = Trie()
trie.insert(strs[mini])
prefixLen = len(strs[mini])
for i in range(len(strs)):
prefixLen = trie.lcp(strs[i], prefixLen)
return strs[0][:prefixLen]Where is the length of the shortest string and is the number of strings.