My 3ms solution


  • 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.