Leetcode#14 Longest Common Prefix

less than 1 minute read

Published:

https://leetcode.com/problems/longest-common-prefix/description/

Idea:

Iteration

Solution:

class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if (strs.size() == 0)
                return "";
            string res = "";
            for (int i=0; i<strs[0].size(); i++) {
                for (int j = 1; j<strs.size(); j++) {
                    if (strs[j].size() < i+1 || strs[j][i] != strs[0][i])
                        return res;
                }
                res.push_back(strs[0][i]);
            }
            return res;
        }
};