Accepted 4ms c++ solution, easy understand.


  • 0
    class Solution {
    public:
        std::string longestCommonPrefix(std::vector<std::string> &strs) {
    		if (strs.empty()) {
    			return std::string("");
    		} else if (strs.size() == 1) {
    			return strs[0];
    		} else {
    			std::sort(strs.begin(), strs.end());
    			int length = 0, size = std::min(strs[0].size(), strs[strs.size() - 1].size());
    			while (length <  size && strs[0][length] == strs[strs.size() - 1][length]) {
    				++length;
    			};
    			return strs[0].substr(0, length);
    		}
        }
    };

Log in to reply
 

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