leetcode

最长公共前缀(leetcode_14)

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 “”。

示例 1:

输入: [“flower”,”flow”,”flight”]
输出: “fl”
示例 2:

输入: [“dog”,”racecar”,”car”]
输出: “”
解释: 输入不存在公共前缀。

这题可以先让一个字符字符串等于第一个字符串,然后循环剪切第一个字符串。


#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Solution
{
public:
    string longestCommonPrefix(vector<string> &strs)
    {
        if (strs.empty())
            return "";
        string prefix = strs[0];
        for (int i = 0; i < strs.size(); ++i)
        {
            if (prefix.empty())
                return "";
            while (!prefix.empty() && strs[i].find(prefix) != 0)
                prefix.pop_back();
        }
        return prefix;
    }
};

int main()
{
    vector<string> tmp;
    tmp.push_back("flower");
    tmp.push_back("flow");
    tmp.push_back("flight");
    Solution solute;
    cout << solute.longestCommonPrefix(tmp) << endl;
    return 0;
}

 

Leave a Reply

邮箱地址不会被公开。 必填项已用*标注