3ms,C++ solution using SORT,beats 100% temporarily


  • 2
    X
    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            if (strs.empty())
                return string();
            if (strs.size() == 1)
                return strs[0];
            sort(begin(strs), end(strs));//sort
    	auto sz = min(strs[0].size(), strs[strs.size() - 1].size());
    	decltype(sz) i = 0;
            //only need to compare the first string and the last one
    	while (i < sz && strs[0][i] == strs[strs.size() - 1][i]) {
    		++i;//only need to record the index
    	}
    	return string(begin(strs[0]), begin(strs[0]) + i);
        }
    };
    

  • 0
    D
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.