Good fast C++ code


  • 0
    K

    Here is a simple fast c++ solution:

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) 
        {
            if (strs.size() == 0)
                return "";
            int maxL = strs[0].length();
            bool match = true;
            int j = 0;
            for (int i = 1; i < strs.size(); i++)
            {
                if ((strs[i]).length() == 0 || (strs[i])[0] != (strs[0])[0])
                    return "";
                while (match && j < maxL && j < strs[i].length())
                {
                    match = ((strs[i])[j] == (strs[0])[j]);
                    j++;
                }
                if (!match)
                    maxL = j - 1;
                if (strs[i].length() < maxL)
                    maxL = strs[i].length();
                j = 0;
                match = true;
            }
            return strs[0].substr(0, maxL);
        }
    };
    

    It starts with the top string and only stores the length of the longest prefix. It then goes through each next string, and only determines how much shorter the length of the max prefix is. At the end, it applies the current longest length to the first string, and you have your longest prefix.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.