Leetcode 14 Solution

This article provides solution to leetcode question 14 (longest-common-prefix)

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

Thinking Process

This is a very straightforward question, just scan them will give us the answer.

Time & Space Complexity

Assuming M is the number of strings, and N is the average length of the string

  • Time complexity: O(M * N)
  • Space complexity: O(1)

This is the optimal solution to the problem, because you can’t solve the problem without even looking at the strings, and simply looking at the strings take O(M * N) time.

Solution

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.size() == 0)
            return "";

        int pos = 0;
        string cpre;

        while (true)
        {
            bool matched = true;
            char ch;

            for (int i = 0; i < strs.size(); i++)
            {
                if (pos >= strs[i].length())
                {
                    matched = false;
                    break;
                }

                if (i == 0)
                {
                    ch = strs[i][pos];
                }
                else if (ch != strs[i][pos])
                {
                    matched = false;
                    break;
                }
            }

            if (matched == false)
                break;

            cpre += ch;
            pos++;
        }

        return cpre;
    }
};