A brute-force solution


  • 0
    L
    class Solution {
    public:
        string longestCommonPrefix(vector<string> &strs) {
    		if (strs.empty())
    			return string();
    
    		string ans = strs.front();
    		for (const auto & str : strs) {
    			int len = min(ans.length(), str.length());
    			int i = 0;
    			while (i < len && ans[i] == str[i])
    				++i;
    			ans.resize(i);
    			if (ans.empty())
    				return move(ans);
    		}
    		return move(ans);
        }
    };

Log in to reply
 

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