[LeetCode] Longest Common Prefix

题意

给出 N 个字符串,求这 N 个字符串的最长公共前缀。

题解

不带坑。二重循环做就好。

代码

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) == 0:
            return ""

        ans = strs[0]
        for s in strs:
            for i in range(min(len(s), len(ans))):
                if ans[i] != s[i]:
                    ans = ans[0:i]
                    break
            else:
                ans = ans[0:min(len(s), len(ans))]

            if ans == '':
                break
        return ans

Python 的奇葩语法:For...Else:如果 for 循环正常结束,那么执行 else;如果 for 循环被打破,那么什么也不干。

结果

117 / 117 test cases passed.
Status: Accepted
Runtime: 56 ms
Your runtime beats 57.87% of pythonsubmissions.

桩程序

if __name__ == '__main__':
    cases = [
        {'strs': ['abc', 'ab'], 'ans': 'ab'},
        {'strs': ['abcd', 'abc', 'ab'], 'ans': 'ab'},
        {'strs': ['abcd', 'abc', 'cab'], 'ans': ''},
        {'strs': ['abcd', 'abc', ''],'ans':''},
    ]
    for item in cases:
        ans = (Solution()).longestCommonPrefix(strs=item['strs'])
        print(str(ans == item['ans']) + "\t=>" + str(ans) + ":" + str(item['ans']))

留下评论