classSolution: # 定義一個輸入List[str], 輸出為str的 方法 deflongestCommonPrefix(self, strs: List[str]) -> str: ifnot strs: return"" # Assume the first string is the common prefix prefix = strs[0] for s in strs[1:]: while s[:len(prefix)] != prefix and prefix: # Reduce the prefix by one character prefix = prefix[:-1] ifnot prefix: break return prefix
sol = Solution() print(sol.Solution.longestCommonPrefix(["flower", "flow", "flight"])) #輸出"fl" print(sol.Solution.longestCommonPrefix(strs1)) # 與上相同