diff --git a/README.md b/README.md index 2bf93af3..b4fe66ed 100644 --- a/README.md +++ b/README.md @@ -548,7 +548,7 @@ LeetCode |17|[Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [C++](./algorithms/cpp/letterCombinationsOfAPhoneNumber/letterCombinationsOfAPhoneNumber.cpp)|Medium| |16|[3Sum Closest](https://leetcode.com/problems/3sum-closest/)| [C++](./algorithms/cpp/3SumClosest/3SumClosest.cpp)|Medium| |15|[3Sum](https://leetcode.com/problems/3sum/)| [C++](./algorithms/cpp/3Sum/3Sum.cpp)|Medium| -|14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)| [C++](./algorithms/cpp/longestCommonPrefix/longestCommonPrefix.cpp)|Easy| +|14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)| [C++](./algorithms/cpp/longestCommonPrefix/longestCommonPrefix.cpp) [Python](./algorithms/python/longestCommonPrefix/longestCommonPrefix.py)|Easy| |13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [C++](./algorithms/cpp/romanToInteger/romanToInteger.cpp)|Easy| |12|[Integer to Roman](https://leetcode.com/problems/integer-to-roman/)| [C++](./algorithms/cpp/integerToRoman/integerToRoman.cpp)|Medium| |11|[Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [C++](./algorithms/cpp/containerWithMostWater/containerWithMostWater.cpp), [Java](./algorithms/java/src/containerwithmostwater.java)|Medium| diff --git a/algorithms/python/LongestCommonPrefix/longestCommonPrefix.py b/algorithms/python/LongestCommonPrefix/longestCommonPrefix.py new file mode 100644 index 00000000..5ff4e9a5 --- /dev/null +++ b/algorithms/python/LongestCommonPrefix/longestCommonPrefix.py @@ -0,0 +1,17 @@ +def longest_common_prefix(strs): + if not strs: + return "" + + prefix = strs[0] + + for s in strs[1:]: + while s[:len(prefix)] != prefix and prefix: + prefix = prefix[:-1] + if not prefix: + return "" + + return prefix + +if __name__ == "__main__": + strs = ["abab", "aba", "abc"] + print(longest_common_prefix(strs))