Share my Java solution:213ms


  • 0
    Y
    public class Solution {
        public int compareVersion(String version1, String version2) {
        	return compare(trimInput(version1).split("\\."),trimInput(version2).split("\\."));
        }
        public String trimInput(String version){
        	String retVal = version;
        	int idx = version.lastIndexOf(".");
        	if(idx>0){
        	while(Integer.parseInt(retVal.substring(idx+1,retVal.length()))==0){
        		retVal = version.substring(0,idx);
        		idx = retVal.lastIndexOf(".");
        	}
        	}
        	return retVal;
        }
        public int compare(String[] v1,String[] v2){
        	int retVal=0;
        	for(int i = 0;i<(v1.length<v2.length?v1.length:v2.length)&&retVal==0;i++){
        		if(Integer.parseInt(v1[i])<Integer.parseInt(v2[i])){
        			retVal = -1;
        		}else if(Integer.parseInt(v1[i])>Integer.parseInt(v2[i])){
        			retVal = 1;
        		}
        	}
        	if(v1.length!= v2.length){
        		if(retVal==0){
        			if(v1.length>v2.length){
        				retVal = 1;
        			}else{
        				retVal = -1;
        			}
        		}
        	}
        	return retVal;
        }
    }

Log in to reply
 

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