Sunday, November 30, 2014

Longest Common Prefix

    string longestCommonPrefix(vector<string> &strs) {
         string res;
        if (strs.empty()) return res;
        for (int i = 0; i < strs[0].size(); ++i)
        {
            char ch = strs[0][i];
            for (int j = 1; j < strs.size(); ++j)
                if (i == strs[j].size() || strs[j][i] != ch)
                    return res;
            res.push_back(ch);
        }
        return res;
    }

No comments:

Post a Comment