3ms Clean C++ solution


  • 0
    X
    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            vector<int> vervec1;
            vector<int> vervec2;
            
            splitVersionString(version1, vervec1);
            splitVersionString(version2, vervec2);
            
            int maxI = max(vervec1.size(), vervec2.size());
            int i;
            for (i=0; i<maxI; ++i)
            {
                int v1 = i<vervec1.size() ? vervec1[i] : 0;
                int v2 = i<vervec2.size() ? vervec2[i] : 0;
                
                if (v1 < v2)
                {
                    return -1;
                }
                else if (v1 > v2)
                {
                    return 1;
                }
            }
            
            return 0;
        }
        
    private:
        static void splitVersionString(string version,
                                  vector<int>& vervec)
        {
            int tmp = 0;
            for(size_t i=0; i<version.size(); ++i)
            {
                if (version[i] == '0' && tmp == 0)
                {
                    continue;
                }
                else if (version[i] != '.')
                {
                    tmp = tmp * 10 + atoi(&version[i]);
                }
                else
                {
                    vervec.push_back(tmp);
                    tmp = 0;
                }
            }
            
            vervec.push_back(tmp);
        }
    };

  • 0
    H
    class Solution {
        public:
            int compareVersion(string version1, string version2) {
                vector<int> v1, v2; 
                str2num((char*)version1.c_str(), &v1);
                str2num((char*)version2.c_str(), &v2);
                vector<int>::iterator it_1 = v1.begin(), it_2 = v2.begin();
                while(it_1 != v1.end() && it_2 != v2.end()) {
                    if(*it_1 != *it_2) {
                        return *it_1 > *it_2 ? 1 : -1; 
                    }   
                    it_1++;
                    it_2++;
                }  
                while(it_1 != v1.end() && *it_1 == 0) {
                    it_1++;
                }
                while(it_2 != v2.end() && *it_2 == 0) {
                    it_2++;
                }
                if(it_1 == v1.end() && it_2 == v2.end()) {
                    return 0;
                }   
                return it_1 == v1.end() ? -1 : 1;
            }   
            void str2num(char* p, vector<int>* n) {
                char* s  = strtok(p, ".");  
                while(s) {
                    n->push_back(atoi(s));
                    s = strtok(NULL, ".");
                }   
            }  
        };

Log in to reply
 

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