【LeetCode】Longest Common Prefix

版权声明: https://blog.csdn.net/ysq96/article/details/89671769

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.

题意:

找到最长的公共长缀,依次判断,因为这是取从前往后的最长交集,那只需要每次用不断精确的交集与当前字符串比较即可。

C++:注意判断给的字符串数组为空的情况

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

Python3:python版我是参考别人的解法

利用python的max()和min(),在Python里字符串是可以比较的,按照ascII值排,举例abb, aba,abac,最大为abb,最小为aba。所以只需要比较最大最小的公共前缀就是整个数组的公共前缀

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        s1 = min(strs)
        s2 = max(strs)
        for i,x in enumerate(s1):
            if x != s2[i]:
                return s2[:i]
        return s1

猜你喜欢

转载自blog.csdn.net/ysq96/article/details/89671769
今日推荐