LeetCode.14. Longest Common Prefix(最长公共前缀)

来源:互联网 发布:sql函数的种类 编辑:程序博客网 时间:2024/05/18 01:45

Write a function to find the longest common prefix string amongst an array of strings.

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        if(strs.size() == 0) return "";        string b = "";        for(int index=0; index < strs[0].size(); index ++)  //以第一个字符串为基准,对比其他所有剩余的字符串        {                     for(int i=1; i<strs.size();i++) //循环遍历所有剩下的字符串            {                if(strs[i][index] != strs[0][index]) //只要发现剩余的字符串的其中一个的某个位置与第一个字符串的不同,则输出子字符串                {                                       for(int j=0; j<index; j++)                    {                        b += strs[0][j]; //字符串的拼接string类                    }                    return b;                }            }        }        return strs[0];  //此时说明所有的字符串都相同也包括只有一个字符串的时候。    }};

python :

class Solution(object):    def longestCommonPrefix(self, strs):        """        :type strs: List[str]        :rtype: str        """        if not strs:            return ""               for i, letter in enumerate(zip(*strs)):            if(len(set(letter)) >1 ):                return strs[0][:i]        return min(strs)        


阅读全文
0 0
原创粉丝点击