A java solution


  • 1
    H
    public int compareVersion(String version1, String version2) {
        int start1 = 0;
        int start2 = 0;
        while (start1 < version1.length() || start2 < version2.length()) {
            int dotIndex1 = findDot(version1, start1);
            int dotIndex2 = findDot(version2, start2);
            int val1 = atoi(version1, start1, dotIndex1 - 1);
            int val2 = atoi(version2, start2, dotIndex2 - 1);
            if (val1 > val2) return 1;
            if (val1 < val2) return -1;
            start1 = dotIndex1 + 1;
            start2 = dotIndex2 + 1;
        }
        return 0;
    }
    
    private int findDot(String s, int start) {
        int index = start;
        while (index < s.length()) {
            if (s.charAt(index) == '.') break;
            index++;
        }
        return index;
    }
    
    private int atoi(String s, int start, int end) {
        int val = 0;
        for (int i = start; i <= end; ++i) {
            val = val * 10 + (s.charAt(i) - '0');
        }
        return val;
    }

Log in to reply
 

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