leetcode 14 Longest Common Prefix

Java:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0) return "";
        
        String pre = strs[0];
        int i = 1;
        while(i <= strs.length-1){
            //.indexOf() 返回字符第一次出现的位置
            while(strs[i].indexOf(pre)!=0){
                //.substring(s,e) 截取s到e-1的字段
                pre = pre.substring(0, pre.length()-1);
            }
            i++;
        }
        return pre;
    }
}

Python:

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        
        for i, let in enumerate(zip(*strs)):
            if len(set(let))>1:
                return strs[0][:i]
        else:
            return min(strs)
        
        '''
        zip用法
        >>>a = [1,2,3]
        >>> b = [4,5,6]
        >>> c = [4,5,6,7,8]
        >>> zipped = zip(a,b)     # 打包为元组的列表
        [(1, 4), (2, 5), (3, 6)]
        >>> zip(a,c)              # 元素个数与最短的列表一致
        [(1, 4), (2, 5), (3, 6)]
        >>> zip(*zipped)          # 与 zip 相反,可理解为解压,返回二维矩阵式
        [(1, 2, 3), (4, 5, 6)]

        '''

猜你喜欢

转载自blog.csdn.net/mrxjh/article/details/79770521
今日推荐