Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee"

Input : {"apple", "ape", "april"} Output : "ap"

Solution: Character by Character Matching

We can keep shrinking the common prefix by comparing prefix and each word.

    string longestCommonPrefix(vector<string>& strs) {
        if (strs.empty()) return "";

        string prefix = strs.front();
        int index = INT_MAX;
        for (int i=1; i<strs.size(); i++) {
            int j = 0;
            while (j < prefix.size() && j < strs[i].size() && prefix[j] == strs[i][j]) j++;
            prefix = prefix.substr(0, j);
        }
        return prefix;
    }
};

Solution: Word by Word Matching

results matching ""

    No results matching ""