My c++ accepted code


  • 0
    L
       string longestCommonPrefix(vector<string> &strs) {
    	if (!strs.size()) return string();
    	else if (strs.size()==1) return strs[0];
    	
    	int prefixLen = strs[0].length();
    	int i,j;
    	for (i=1; i<strs.size(); i++) {
    		prefixLen = (prefixLen>strs[i].length()) ? strs[i].length() : prefixLen;
    		for (j=0; j<prefixLen; j++) {
    			if (strs[0][j]!=strs[i][j]) break;
    		}
    		if (j==0) return string();
    		prefixLen = j;
    	}
    	return strs[0].substr(0, prefixLen);
       }

Log in to reply
 

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