0014.最长公共前缀

方法一:纵向扫描

时间复杂度 $O(mn)$,空间复杂度 $O(1)$。

func longestCommonPrefix(strs []string) string {
    for i := 0; i < len(strs[0]); i++ {
        for j := 1; j < len(strs); j++ {
            if len(strs[j]) < i+1 || strs[j][i] != strs[0][i] {
                return strs[0][:i]
            }
        }
    }
    return strs[0]
}
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        for i in range(len(strs[0])):
            for s in strs[1:]:
                if len(s) <= i or s[i] != strs[0][i]:
                    return s[:i]
        return strs[0]