sourcecode

Monday, February 23, 2015

Longest Common Prefix

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

 class Solution {
public:
    string longestCommonPrefix(vector &strs) {
        if (strs.size() < 1) return "";
        string pre = strs[0];
        for(int index = 0; index < pre.length(); ++index) {
            for(int ii = 0; ii < strs.size(); ++ii) {
                string current = strs[ii];
                if (current[index] != pre[index]) return pre.substr(0, index);
            }
        }
        return pre;
    }
};

No comments: