Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions 0014/longest_common_prefix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Time: O(n * k), k is the length of the common prefix
# Space: O(1)

class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""

for i in xrange(len(strs[0])):
for string in strs[1:]:
if i >= len(string) or string[i] != strs[0][i]:
return strs[0][:i]
return strs[0]


# Time: O(n * k), k is the length of the common prefix
# Space: O(k)
class Solution2(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
prefix = ""

for chars in zip(*strs):
if all(c == chars[0] for c in chars):
prefix += chars[0]
else:
return prefix

return prefix
25 changes: 25 additions & 0 deletions 0014/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
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.