13.力扣c++刷题-->最长公共前缀

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

#include
#include
#include
#include
#include
using namespace std;

class Solution 
{
public:
    string longestCommonPrefix(vector<string>& strs)
    {
       int size = strs.size();
       string per = strs[0];

       for (int i = 1; i < size; i++)
       {
            for (int j = 0; ((j < per.length()) && (j < strs[i].length())); j++)
            {
                if (per[j] != strs[i][j])
                {
                    cout << per[j] << " " << strs[i][j] << endl;
                    if (j == 0)
                    {
                        return "";
                    }
                    else
                    {
                       per = per.substr(0, j);
                       cout << per << endl;
             
                       break;
                    }
                }
            }
       }
       return per;
    }
};

int main()
{
    vector<string> strs1 = { "flower","flow","flight" };
    vector<string> strs2 = { "dog","racecar","car" };

    Solution a;
    cout <<"a.isPalindrome : " << a.longestCommonPrefix(strs2) << endl;

    return 0;
}

你可能感兴趣的:(c++力扣刷题,c++,leetcode,算法)