Skip to content

Latest commit

 

History

History
33 lines (22 loc) · 882 Bytes

0014. 最长公共前缀.md

File metadata and controls

33 lines (22 loc) · 882 Bytes
  • 标签:字符串
  • 难度:简单

题目大意

给定一个字符串数组,返回最长公共前缀。

解题思路

直接纵向遍历,依次遍历每个字符串,比较相同位置上的字符是否相同,如果不相同则这一列字母不属于公共前缀,直接返回之前的公共前缀。如果相同,则继续对下一列进行比较。

代码

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""

        length = len(strs[0])
        count = len(strs)
        for i in range(length):
            c = strs[0][i]
            for j in range(1, count):
                if len(strs[j]) == i or strs[j][i] != c:
                    return strs[0][:i]
        return strs[0]