卖萌的弱渣

I am stupid, I am hungry.

Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

Solution

  • Java File /Users/minli/Desktop/Personal/sdytlm.github.io/source/downloads/code/LeetCode/Java/Longest-Common-Prefix.java could not be found

  • Python

(Longest-Common-Prefix.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        ret = ""
        n = len(strs)
        if n == 0:
            return ret
        for cur in range(len(strs[0])):
            c = strs[0][cur]
            for i in range(1,n):
                # cur可能超过strs[i]的长度
                if cur >= len(strs[i]) or strs[i][cur] != c:
                    return strs[0][:cur]
        return strs[0]