Accepted Java code


  • 0
    public int compareVersion(String s1, String s2) {
        int n1 = s1.length(), n2 = s2.length();
        int i = 0, j = 0;
        int v1 = 0, v2 = 0;
        
        while (i < n1 && j < n2) {
            while (i < n1 && s1.charAt(i) != '.') {
                v1 = v1 * 10 + (int)(s1.charAt(i++) - '0');
            }
            
            while (j < n2 && s2.charAt(j) != '.') {
                v2 = v2 * 10 + (int)(s2.charAt(j++) - '0');
            }
            
            if (v1 > v2) return 1;
            if (v2 > v1) return -1;
            
            v1 = 0; v2 = 0;
            i++; j++;
        }
        
        while (i < n1 && s1.charAt(i) != '.') {
            v1 = v1 * 10 + (int)(s1.charAt(i++) - '0');
        }
        
        while (j < n2 && s2.charAt(j) != '.') {
            v2 = v2 * 10 + (int)(s2.charAt(j++) - '0');
        }
        
        if (v1 > v2) return 1;
        if (v2 > v1) return -1;
        
        return 0;
    }

Log in to reply
 

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