首页 > 代码库 > Longest Common Prefix
Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
(每个字符串从0开始的公共部分即最长公共前缀)
C++代码如下:
#include<iostream>#include<string>#include<vector>using namespace std;class Solution {public: string longestCommonPrefix(vector<string> &strs) { if(strs.empty()) return ""; string s1=strs[0]; string s2; size_t len=s1.size(); for(size_t i=1;i<strs.size();i++) { s2=strs[i]; if(s2.size()<len) len=s2.size(); for(size_t j=0;j<len;j++) { if(s1[j]!=s2[j]) { len=j; break; } } } return s1.substr(0,len); }};int main(){ vector<string> vec={"aaaaai","aaaaa","aaaa","aaab","aaaagg"}; Solution s; cout<<s.longestCommonPrefix(vec)<<endl;}
运行结果:
Longest Common Prefix
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。