Longest Common Prefix

Problem Id: 14 Difficulty: Easy Tag: String


Intuition

Brute force!!

Solution


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

        index = 0
        while True:
            match = True
            c = None
            for i in range(len(strs)):
                if index >= len(strs[i]):
                    match = False
                    break
                if c is None:
                    c = strs[i][index]
                elif c != strs[i][index]:
                    match = False
                    break
            if not match:
                break
            index += 1
        return strs[0][:index]