14.最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""

示例1.
输入: ["flower","flow","flight"]
输出: "fl"
示例2.
输入:["ca","a"]
输出: ""

暴力复杂度O(k*n)

第一个字符串长度:k
字符串个数:n
string:find

npos 是这样定义的:
static const size_type npos = -1;

c++ code:此代码代表:最长公共子串

class Solution {
public:
    string longestCommonPrefix(vector& strs) {
        string res = "";
        if (strs.empty())return res;
        vectorpos(strs.capacity(),-1);//初始化为capacity个-1
        for (int i = 0; i 

核心c++ code :最长公共前缀 AC 99.8% 签到

class Solution {
public:
    string longestCommonPrefix(vector& strs) {
        string res = ""; int flag = 0;
        if (strs.empty() )return res;
        if (strs.capacity() == 1)return strs[0];
        int minlen = 0;
        for (int i = 0; i < strs.capacity() - 1; i++)
        {
            if (strs[i].length() < strs[i + 1].length())
                minlen = strs[i].length();
            else
                minlen = strs[i+1].length();
        }

        for (int i = 0; i 

最长公共前缀 ,完整c++代码:

#include
#include
#include
#include
#include
#include
#include


using namespace std;

class Solution {
public:
    string longestCommonPrefix(vector& strs) {
        string res = ""; int flag = 0;
        if (strs.empty() )return res;
        if (strs.capacity() == 1)return strs[0];
        int minlen = 0;
        for (int i = 0; i < strs.capacity() - 1; i++)
        {
            if (strs[i].length() < strs[i + 1].length())
                minlen = strs[i].length();
            else
                minlen = strs[i+1].length();
        }

        for (int i = 0; i  stringToStringVector(string input) {
    vector output;
    trimLeftTrailingSpaces(input);
    trimRightTrailingSpaces(input);
    input = input.substr(1, input.length() - 2);
    stringstream ss;
    ss.str(input);
    string item;
    char delim = ',';

    while (getline(ss, item, delim)) {
        item = item.substr(1, item.length() - 2);
        output.push_back(item);
    }
    return output;
}

int main() {
    string line;
    while (getline(cin, line)) {
        vector height = stringToStringVector(line);

        string ret = Solution().longestCommonPrefix(height);

         
        cout << ret << endl;
    }
    return 0;
}

你可能感兴趣的:(14.最长公共前缀)