Longest Common Prefix-LeetCode

来源:互联网 发布:js按钮置灰 不可点击 编辑:程序博客网 时间:2024/04/29 04:11

Write a function to find the longest common prefix string amongst an array of strings.

class Solution {public:    string longestCommonPrefix(vector<string> &strs) {        if (strs.empty()||strs[0].empty())    {    return "";    }    vector <char> pre;    pre.push_back(strs[0][0]);    for (unsigned int i = 0; i < pre.size() ; i++)    {    for (unsigned int j = 0; j < strs.size(); j++)    {    if (strs[j].empty())    {    return "";    }    if (i >= strs[j].size() || pre[i] != strs[j][i])    {    return strs[0].substr(0,i);    }    }    if (i < strs[0].length() - 1)    {    pre.push_back(strs[0][i + 1]);    }    else    {    return strs[0];    }    }    }};


 

0 0
原创粉丝点击