-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
chenzhengwei
committed
May 23, 2017
1 parent
e7d18f4
commit 69d7e4e
Showing
2 changed files
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
``` |