diff --git a/README.md b/README.md index a7f7a13..5fb8992 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,8 @@ leetcode 题解 [9. Palindrome Number](Solution/1-50/9.md) +[14. Longest Common Prefix](Solution/1-50/14.md) + [19. Remove Nth Node From End of List](Solution/1-50/19.md) [21. Merge Two Sorted Lists](Solution/1-50/21.md) diff --git a/Solution/1-50/14.md b/Solution/1-50/14.md new file mode 100644 index 0000000..faabc92 --- /dev/null +++ b/Solution/1-50/14.md @@ -0,0 +1,26 @@ +# 14. Longest Common Prefix +[题目链接](https://leetcode.com/problems/longest-common-prefix/#/description) +```python +class Solution(object): + def longestCommonPrefix(self, strs): + """ + :type strs: List[str] + :rtype: str + """ + if len(strs) == 0: + return '' + prefix = strs[0] + for data in strs: + length = len(prefix) + # 如果前缀的长度比字符串长,则交换 + if len(data) < length: + prefix , data = data, prefix + length = len(prefix) + while data[:length] != prefix: + prefix = prefix[:-1] + length -= 1 + # 如果长度为0,意味着没有公共前缀,所以返回0 + if length == 0: + return '' + return prefix +``` \ No newline at end of file