Longest common prefix

本文详细介绍了使用C++实现最长公共前缀算法的过程,并通过代码实例进行了演示。算法从字符串数组中找出所有字符串共有的最长起始部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 class Solution {
 2 public:
 3     string longestCommonPrefix(vector<string> &strs) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         string result;
 7         if (strs.size() == 0) return result;
 8         if (strs.size() == 1){
 9             
10             if (strs[0].size() == 0) return result;
11             result.push_back(strs[0][0]);
12             return result;
13         }
14         
15         int minLength = INT_MAX;
16         for (int i=0; i<strs.size(); i++){
17             
18             if (strs[i].size() == 0) return result;
19             else if (strs[i].size() < minLength) minLength = strs[i].size();
20         }
21         
22         for (int j = 0; j<minLength; j++)
23             for (int i = 0; i<strs.size()-1; i++){
24                 
25                 if (strs[i][j] == strs[i+1][j]){
26                     
27                     if (i == strs.size()-2) result.push_back(strs[i][j]);
28                 }
29                 
30                 else return result;
31             }
32     }
33 };

 

转载于:https://www.cnblogs.com/tanghulu321/archive/2013/05/13/3074990.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值