Clean C++ solution, 0ms, no split, no extra space, no stream operation.


  • 2
    W
    int compareVersion(string s1, string s2) {
        int n1 = s1.size(), n2 = s2.size();
        int p1 = 0, p2 = 0;
        while (p1 < n1 || p2 < n2) {
            auto v1 = p1 < n1 ? sub_version(s1, p1) : 0;
            auto v2 = p2 < n2 ? sub_version(s2, p2) : 0;
            if (v1 > v2) return 1;
            if (v1 < v2) return -1;
        }
        return 0;
    }
    
    int sub_version(const string &s, int &pos) {
        auto num = 0;
        while (pos < s.size() && s[pos] != '.')
            num = num * 10 + s[pos++] - '0';
        ++pos;
        return num;
    }
    

Log in to reply
 

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