My Java Solution


  • 0
    public int compareVersion(String version1, String version2) {
        ArrayList<Integer> num1 = getNumber(version1);
        ArrayList<Integer> num2 = getNumber(version2);
        int i=0;
        for(; i<Math.max(num1.size(), num2.size()); i++) {
            int tmp1 = i<num1.size() ? num1.get(i) : 0;
            int tmp2 = i<num2.size() ? num2.get(i) : 0;
            if(tmp1 > tmp2) return 1;
            if(tmp1 < tmp2) return -1;
        }
        return 0;
    }
    
    public ArrayList<Integer> getNumber(String str) {
        ArrayList<Integer> result = new ArrayList<>();
        int anchor=0, index=0;
        while(index < str.length()) {
            if(str.charAt(index) == '.') {
                result.add(Integer.parseInt(str.substring(anchor, index)));
                anchor = index+1;
            }
            index++;
        }
        if(anchor != index) result.add(Integer.parseInt(str.substring(anchor, index)));
        return result;
    }

Log in to reply
 

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