From 8ea5b71e0f240bda6bc3341f395915ddb5c09678 Mon Sep 17 00:00:00 2001 From: Manas Bhilare Date: Fri, 8 Oct 2021 00:31:40 +0530 Subject: [PATCH] Adding a file --- 0014/longest_common_prefix.py | 36 +++++++++++++++++++++++++++++++++++ 0014/readme.md | 25 ++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 0014/longest_common_prefix.py create mode 100644 0014/readme.md diff --git a/0014/longest_common_prefix.py b/0014/longest_common_prefix.py new file mode 100644 index 0000000..27aee73 --- /dev/null +++ b/0014/longest_common_prefix.py @@ -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 diff --git a/0014/readme.md b/0014/readme.md new file mode 100644 index 0000000..b9a0dd8 --- /dev/null +++ b/0014/readme.md @@ -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.