Simple C++ solution, easy to follow


  • 0
    J

    '''

    vector<string> split(string s, string c = ".")
    {
        vector<string> ret;
        while (s != "")
        {
            int p = s.find_first_of(c);
            if (p == string::npos) break;
            ret.push_back(s.substr(0, p));
            s = s.substr(p + 1);
        }
        
        ret.push_back(s);
        return ret;
    }
    
    bool greater(string &a, string &b)
    {
        while (a.size() > 1 && a[0] == '0') a = a.substr(1);
        while (b.size() > 1 && b[0] == '0') b = b.substr(1);
        
        if (a.size() > b.size()) return true;
        else if (a.size() < b.size()) return false;
        else return a > b;
    }
    
    int compareVersion(string version1, string version2) {
        auto v1 = split(version1);
        auto v2 = split(version2);
        int n1 = v1.size(), n2 = v2.size(), n = max(n1, n2);
        v1.resize(n, "0");
        v2.resize(n, "0");
        for (int i = 0;i < n; i++)
        {
            if (greater(v1[i], v2[i])) return 1;
            else if (greater(v2[i], v1[i])) return -1;
        }
        
        return 0;
    }
    

    '''


Log in to reply
 

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