LeetCode 14. Longest Common Prefix

本文介绍了两种寻找字符串数组中最长公共前缀的方法:逐一比较法和排序比较法,并提供了详细的算法实现。

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


Compare one by one, get the common prefix.

    string longestCommonPrefix(vector<string>& strs) {
    if(strs.size() == 0) return "";
    if(strs.size() == 1) return strs[0];
    string a = strs[0];
    string res;
    for(int i = 1; i < strs.size(); ++i) {
        string tmp = "";
        int j = 0;
        int k = 0;
        while(j < a.size() && k < strs[i].size()) {
            if(a[j] == strs[i][k]) {
                tmp= tmp + a[j];
                j++; k++;
            } else break;
        }
        a = tmp;
        res = tmp;
    }
    return res;

    }

Second Round:

To simplify this problem, since we are getting  the common prefix for all the input strings, we just need to first sort the input string alphabetically and compare the first and the last to check how much they overlap.

string longestCommonPrefix(vector<string>& strs) {
  if(strs.size() < 1) return "";
  sort(strs.begin(), strs.end());
  string front = strs[0];
  string end = strs.back();
  for(int i = 0; i < front.size() && i < end.size(); ++i) {
    if(front[i] != end[i]) break;
  }
  return front.substr(0, i);
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值