LeetCode 刷题记录 14. Longest Common Prefix

题目:
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.
方法1:
纵向遍历 以第一个字符串为基准 依次比较各个字符串 如果字符相等则继续 否则说明已经找到公共前缀,注意要防止索引越界
c++:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        
        if(strs.empty()) return "";
       
        for(int j = 0; j < strs[0].size(); j++){
            
            for(int i = 1; i < strs.size(); i++){
                if(j >= strs[i].size() || strs[i][j] != strs[0][j]){
                    return strs[0].substr(0, j);
                }
            }
            
        }
        return strs[0];
        
    }
};

java:

  1. 数组是length 而 字符串是length()
  2. isEmpty() 函数用于ArrayList,HashSet,HashMap和String
  3. 判断为空还要考虑空指针
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs == null || strs.length == 0) return "";
       
        for(int j = 0; j < strs[0].length(); j++){
            
            for(int i = 1; i < strs.length; i++){
                if(j >= strs[i].length() || strs[i].charAt(j) != strs[0].charAt(j)){
                    return strs[0].substring(0, j);
                }
            }
            
        }
        return strs[0];
    }
}

Python:
zip函数对应的元素打包成一个个元组,然后返回由这些元组组成的列表
zip(*strs)将对应的字符串字符打包,而zip(strs)打包整个字符串
set函数 排除重复元素

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs: return ''
        l = 0
        
        for cg in zip(*strs):
            
            if len(set(cg)) > 1:
                return strs[0][:l]
            l += 1
        return strs[0][:l]

方法2:
对字符串排序,这样拥有最少匹配的字符串将在首尾的位置,接着只需比较首尾字符串
c++:
back和front函数指向vector的尾部和首部元素

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        
        if(strs.empty()) return "";
       
        sort(strs.begin(), strs.end());
        int n = min(strs[0].size(), strs.back().size());
        for(int i = 0; i < n; i++){
            if(strs[0][i] != strs.back()[i]) return strs[0].substr(0, i);
        }
        return strs[0];
        
    }
};

java:
排序:Arrays.sort(strs);

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs == null || strs.length == 0) return "";
        Arrays.sort(strs);
        int n = Math.min(strs[0].length(), strs[strs.length - 1].length());
        for(int i = 0; i < n; i++){
            if(strs[0].charAt(i) != strs[strs.length - 1].charAt(i)) return strs[0].substring(0, i);
        }
        
        return strs[0];
    }
}

python:
排序:strs.sort()

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs: return ''
        strs.sort()
        n = min(len(strs[0]), len(strs[-1]))
        i = 0
        
        while i < n and strs[0][i] == strs[-1][i]:
            i += 1
            
        return strs[0][:i]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值