3ms clean and easy-to-understand C++ solution based on stringstream


  • 1
    X
    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            stringstream ss1(version1), ss2(version2);
            
            do {
                int v1 = getVersion(ss1);
                int v2 = getVersion(ss2);
                int diff = v1 - v2;
                if (diff != 0)
                    return diff > 0 ? 1 : -1;
            } while (!ss1.eof() || !ss2.eof());
            
            return 0;
        }
        
        int getVersion(stringstream &ss) {
            if (ss.eof())     return 0;
            
            string s;
            getline(ss, s, '.');
            return stoi(s);
        }
    };

Log in to reply
 

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