Leetcode – Longest Common Prefix

Name: Longest Common Prefix
Difficulty: Easy
Description: Find the longest common prefix amongst several words

Example:

Given ["flower", "flow", "flight"], return "fl"
Given ["car", "tree"], return ""
Given ["c"] return "c"

I was pretty tired when coding this one, time for bed 🙂

string longestCommonPrefix(vector<string>& strs) {
    const string& word = strs[0];

    if (strs.size() == 1) return word;

    for (auto i = 0; i < word.size(); ++i) {
        for (auto j = 1; j < strs.size(); ++j) {
            if (strs[j][i] != word[i]) {
                return i > 0 ? word.substr(0, i) : "";
            }
        }
    }

    return word;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s