Share my Java solution and cases we should consider


  • 0
    D

    Cases:
    (=, .2, 0.2)
    (=, 1.0.0, 1)
    (>, 1.0.1, 1)
    (=, 1..1, 1.0.1)

    , and other trivial cases everyone knows. (What is a valid version number is not defined so some above cases may not be included in OJ)

    We can scan from left to right and compare until we find some version segments are unequal.

    // scan and return current version segment, store start index of next version segment to nxtIdx[0]
    private int getVersion(char[] c, int idx, int[] nxtIdx) {
        if (idx >= c.length) { // this version is finished, return 0 as current version segment
            nxtIdx[0] = c.length;
            return 0;
        }
        int num = 0;
        while (idx < c.length && c[idx] != '.')
            num = num * 10 + (c[idx++]-'0');
        if (idx >= c.length) nxtIdx[0] = idx;
        else /*if (c[i] == '.')*/ nxtIdx[0] = idx+1; // skip the '.'
        return num;
    }
    
    public int compareVersion(String version1, String version2) {
        char[] c1 = version1.toCharArray(); char[] c2 = version2.toCharArray();
        int i = 0; int j = 0;
        // when only one version is finished we should keep scanning another version
        while (i < c1.length || j < c2.length) {
            int[] nxtIdx = new int[1];
            int n1 = getVersion(c1, i, nxtIdx);
            i = nxtIdx[0];
            int n2 = getVersion(c2, j, nxtIdx);
            j = nxtIdx[0];
            if (n1 > n2) return 1;
            else if (n1 < n2) return -1;
        }
        return 0; // equals when both are finished and still no winner
    }

Log in to reply
 

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