share my easy understand java solution


  • 0
    L
    public int compareVersion(String version1, String version2) {
         String[] vs1,vs2;
        if(version1.contains(".")){
            vs1 = version1.split("\\.");
        }else{
            vs1 = new String[]{version1};
        }
        if(version2.contains(".")){
            vs2 = version2.split("\\.");
        }else{
            vs2 = new String[]{version2};
        }
        int len = Math.min(vs1.length,vs2.length);
        int v1,v2;
        for(int i = 0; i < len; i++){
            v1 = Integer.valueOf(vs1[i]);
            v2 = Integer.valueOf(vs2[i]);
            if(v1 < v2){
                return -1;
            }else if(v1 > v2){
                return 1;
            }
        }
        if(vs1.length > vs2.length){
            for(int i = len; i < vs1.length; i++){
                if(Integer.valueOf(vs1[i]) > 0){
                    return 1;
                }
            }
        }else if(vs2.length > vs1.length){
            for(int i = len; i < vs2.length; i++){
                if(Integer.valueOf(vs2[i]) > 0){
                    return -1;
                }
            }
        }
    
        return 0;
    }

Log in to reply
 

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