Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string “”.
Example 1: Input: [“flower”,“flow”,“flight”] Output: “fl”
Example 2: Input: [“dog”,“racecar”,“car”] Output: “” Explanation: There is no common prefix among the input strings.
Note: All given inputs are in lowercase letters a-z. 题意: 给出一个字符串数组,要求找出这些字符串中最长的公共前子串,注意,这些字符串全部都是由小写字母a-z组成。 思路: 先找出字符串数组中最短的那个字符串,得到长度后只需对所有的字符串按位比较是否相等,相等则加入到公共前子串中,不等则返回公共子串。 代码仅供参考:
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ common_str = '' n = len(strs) if n == 0: return common_str len_str = min([len(s) for s in(strs)]) for i in range(len_str): for s in (strs): if s[i] != strs[0][i]: return common_str common_str += strs[0][i] return common_str此题用上述方法可以直接求解,后来看到大神提供了另外一种思路,比较数组中字符串的大小,记录值最小的和最大的字符串,这里要注意了,字符串的大小比较是根据ASCALL码从左至右逐位比较,比如"aasd"就小于"ab***",无论“*”代表什么。在得到最小值和最大值的字符串后,对这两个字符串再进行逐位比较即可,有的人可能会疑惑,这样就能得到最长公共前子串吗?答案是肯定的,因为我们的字符串都是由小写字母“a-z”组成,假如在某一位,有其它字符串与最小值的字符串不等,那么最大值的字符串与最小值的字符串在该位肯定也不等,因为字符串的值是按位比较的,所以这就证实了此方法的可行性,而不用每次都对数组中所有的字符串按位比较。大神!请收下小弟的膝盖! 代码:
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" s1 = min(strs) s2 = max(strs) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1