165 Compare Version Numbers

Compare two version numbers version1 and version2.
If version1 > version2 return 1,
if version1 < version2 return -1,
otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the "." character. The "." character does not represent a decimal point and is used to separate number sequences. For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.
Here is an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37

Solution:

class Solution {
public:
    vector<int> split(string s) {
        s += ".";
        int n = s.size();
        vector<int> res;
        string tmp = "";
        for ( int i = 0; i <= n-1; i++ ) {
            if ( s[i] == '.' ) {res.push_back(atoi(tmp.c_str())); tmp = "";}
            else tmp += s[i];
        }
        return res;
    }
    int compareVersion(string version1, string version2) {
        vector<int> res1 = split(version1), res2 = split(version2);
        int n1 = res1.size(), n2 = res2.size();
        int i1, i2;
        for ( int i = 0; i <= max(n1, n2)-1; i++ ) {
            if ( i >= n1 ) i1 = 0;
            else i1 = res1[i];
            if ( i >= n2 ) i2 = 0;
            else i2 = res2[i];
            if ( i1 > i2 ) return 1;
            if ( i1 < i2 ) return -1;
        }
        return 0;
    }
};

results matching ""

    No results matching ""