Write a function to find the longest common prefix string amongst an array of strings.
Analysis:
Find the longest common prefix for a string.
Because you can only search for the prefix, you can use the first string as the basis and compare it with other strings by character until a string has been traversed or encounters an inconsistent character, returns the prefix of the first string so far.
class Solution: # @return a string def longestCommonPrefix(self, strs): if not strs or not strs[0]: return "" first = strs[0] for i in range(len(first)): for s in strs[1:]: if i >= len(s) or s[i] != first[i]: return first[:i] return firstif __name__ == ‘__main__‘: s = Solution() assert s.longestCommonPrefix([]) == "" assert s.longestCommonPrefix([""]) == "" assert s.longestCommonPrefix(["a", "b"]) == "" assert s.longestCommonPrefix(["aa", "aa"]) == "aa" print ‘PASS‘
Summary:
This problem is relatively simple, and there are not many traps in programming. You can write the code by using an intuitive method to access it.
Longest Common prefix