02.最长公共前缀(leetcode T14)

题目:

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.

解题思路:

(1)水平扫描法:

  • 从前往后枚举字符串的每一列,先比较每个字符串的相同列上的字符,再比较下一列;
  • n个字符串的最长公共前缀,也是第一个字符串和第二个字符串的公共前缀,是之与第三个公共前缀,以此类推;
  • 时间复杂度O(s)。
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string word;//存放最大公共前缀
        if(strs.size() <= 0)
            return "";
        for(int i = 0; i < strs[0].length();i++){
            char c = strs[0][i];
            for(int j = 1; j < strs.size(); j++){
                if(i == strs[j].length() || strs[j][i] != c)
                    return strs[0].substr(0,i);
            }
        }
        return strs[0];
    }
};

(2)分治技巧+递归

  • 先将n个字符串分成两半,分别求两半的最长公共前缀,即lcpLeft和lcpRight(递归),最后比较这两个字符串的公共前缀
  • 时间复杂度O(s),空间复杂度O(mlogn)(递归,栈的调用)。

(3)二分法

  • 所有字符串的公共前缀,最长是所有字符串最短的长度;
  • 每一次查找将字符串二分,丢弃一定不包含答案的那一半。

新的学习内容:

1.c++的string类

2.c++的容器vector

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值