14. Longest Common Prefix

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

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
    }
};

=========

题目:找vector中最长公共前缀,

思路:模拟比较的过程,我们可以看到这些.

按照数组中的第一个字符串开始进行比较,

对第一个字符串中的每一个字符,和其他字符串的相应位置进行比较,如果都相同那么将此字符加入到  待返回字符串中.

-------

string longestCommonPrefix(vector<string>& strs) {
        string re;
        if(strs.empty()) return re;
        for(int i = 0;i<(int)strs[0].size();i++){
            for(int j = 0;j<(int)strs.size();j++){
                if(i>=(int)strs[j].size()) return re;
                if(strs[j][i]==strs[0][i])
                    continue;
                else
                    return re;
            }
            re.push_back(strs[0][i]);
        }
        return re;
    }
原文地址:https://www.cnblogs.com/li-daphne/p/5608040.html