My C++ Solution


  • 0
    class Solution {
    public:
        string longestCommonPrefix(vector<string> &strs) {
            if (strs.empty())
    			return "";
    		string temp = *strs.begin();
    		vector<string>::iterator it = strs.begin()+1;
    		for (; it != strs.end(); it++){
    			int n = temp.size() > (*it).size() ? (*it).size() : temp.size();
    			while (temp.compare(0, n, *it, 0, n) != 0) 
    				n--;
    			temp = temp.substr(0, n);
    		}
    		return temp;
        }
    };

Log in to reply
 

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