LeetCode 14 Longest Common Prefix

难度:easy

代码:

# -*- coding: utf-8 -*-
# @File  : leet_14.py
# @Author: FanyFull
# @Date  : 2021/9/27

from typing import List

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        result = ""
        length = len(strs)
        if (len == 0):
            return result

        if (length == 1):
            return strs[0]

        loop_len = len(strs[0])
        for i in range(0, length):
            if len(strs[i]) == 0:
                return result

            if len(strs[i]) < loop_len:
                loop_len = len(strs[i])

        for i in range(0, loop_len):
            flag = 0
            for j in range(1, length):
                if strs[0][i] != strs[j][i]:
                    flag = 1
                    break

            if flag == 1:
                break

            result += strs[0][i]

        return result


if __name__ == '__main__':
    solution = Solution()
    input = ["flower", "flow", "flight"]
    # input = ["dog","racecar","car"]
    output = solution.longestCommonPrefix(input)
    print(output)

直接暴力遍历。效率也还可以。


LeetCode 14 Longest Common Prefix
http://fanyfull.github.io/2021/09/27/LeetCode-14-Longest-Common-Prefix/
作者
Fany Full
发布于
2021年9月27日
许可协议