Easy understand, C++ 8ms


  • 0
    B

    1st, set prefix = strs[0], the first str in the strs.

    2nd, check every str in strs char by char.

    • if current str is "", return ""
    • if current str is not "", find the min length length_prefix between prefix and strs[i]
    • check char by char.
    • call prefix.substr to cut the prefix

    3nd, return prefix

    class Solution {
    public:
    string longestCommonPrefix(vector<string>& strs) {
    	int length = strs.size();
    	if (length == 0)	return "";
    
    	string prefix = strs[0];
    	for (int i = 1; i < strs.size(); ++i){
    		if (strs[i] == "")
    			return "";
    
    		int j = 0;
    		int length_prefix = (prefix.size() > strs[i].size()) ? strs[i].size() : prefix.size();
    		for (; j < length_prefix; ++j){
    			if (prefix[j] != strs[i][j]){
    				break;
    			}
    		}
    		prefix = prefix.substr(0, j);
    	}
    	return prefix;
    }
    };

Log in to reply
 

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