[LeetCode]Longest Common Prefix

来源:互联网 发布:java接口 英文缩写 编辑:程序博客网 时间:2024/04/28 10:58
class Solution {//1. find out the minimum size string as the pivot string//2. check every other string and update the minSizepublic:    string longestCommonPrefix(vector<string> &strs) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(strs.size() == 0) return string("");int minSize = strs[0].size();int pivotIdx = 0;for(int i = 0; i < strs.size(); ++i)if(strs[i].size() < minSize){minSize = strs[i].size();pivotIdx = i;}for(int i = 0; i < strs.size(); ++i){if(i == pivotIdx) continue;for(int j = 0; j < minSize; ++j){if(strs[i][j] != strs[pivotIdx][j]){minSize = j;break;}}}return strs[pivotIdx].substr(0, minSize);    }};

second time

class Solution {public:    string longestCommonPrefix(vector<string> &strs) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(strs.size() == 0) return string("");                int strIdx = 0;        //choose the smallest string first        for(int i = 1; i < strs.size(); ++i)            if(strs[i].size() < strs[strIdx].size()) strIdx = i;        int commonLen = strs[strIdx].size();        for(int i = 0; i < strs.size(); ++i)        {            if(i == strIdx) continue;            int curLen = 0;            for(int j = 0; j < strs[i].size() && j < commonLen; ++j)            {                if(strs[strIdx][j] == strs[i][j]) curLen++;                else break;            }            commonLen = curLen;        }                return strs[strIdx].substr(0, commonLen);    }};


原创粉丝点击