LeetCode 14 - Longest Common Prefix

来源:互联网 发布:淘宝订单险要求是什么 编辑:程序博客网 时间:2024/06/07 03:21

Roman to Integer

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

My Code

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        if (strs.empty())            return "";        else if (strs.size() == 1)            return strs[0];        int minLen = strs[0].size();        for (int i = 0; i < strs.size() - 1; i++)        {            const string& str1 = strs[i];            const string& str2 = strs[i+1];            int curLen = 0;            for (int j = 0; j < min(str1.size(), str2.size()); j++)                if (str1[j] == str2[j])                    curLen++;                else                    break;            minLen = min(minLen, curLen);        }        //cout << "minLen: " << minLen << endl;        return strs[0].substr(0, minLen);    }};
Runtime: 8 ms

0 0
原创粉丝点击