Tuesday, September 15, 2015

[LeetCode] Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.
class Solution {
    static bool comp(string &s1, string &s2) {
        return s1.length() < s2.length();
    }
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.size() == 0) return "";
        sort(strs.begin(), strs.end(), comp);
        string s = strs[0];
        int len = s.length();
        for(int i=1;i<strs.size();i++) {

            while(strs[i].find(s.substr(0, len)) != 0) len --;
        }
        return s.substr(0, len);
    }
};