Longest Common Prefix

简介: Write a function to find the longest common prefix string amongst an array of strings. (每个字符串从0开始的公共部分即最长公共前缀) C++代码如下: #include #include #incl...

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;
}

运行结果:

相关文章
|
Linux
configure: error: cannot guess build type; you must specify one
configure: error: cannot guess build type; you must specify one
351 0
No plugin found for prefix ‘doclint‘ in the current project
No plugin found for prefix ‘doclint‘ in the current project
97 0
LeetCode之Longest Common Prefix
LeetCode之Longest Common Prefix
88 0
# Leetcode 14:Longest Common Prefix 最长公共前缀
公众号:爱写bug 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 "". 编写一个函数来查找字符串数组中的最长公共前缀。
976 0
[LeetCode]Longest Common Prefix 最长公共前缀
链接:https://leetcode.com/problems/longest-common-prefix/#/description难度:Easy题目:14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings.翻译:编写一个函数来查找给定字符串数组中最长的公共前缀。
919 0