My java solution without split, complicated but accept overflow input


  • 1
    G

    Just posting for anyone's reference, I think it is always better not to assume the input must be int or long, since we'are not doing datatype conversion but value comparison.

    public static int compareVersion(String version1, String version2){
    	int size1 = version1.length(), size2 = version2.length();
    	int v1Start = 0, v2Start = 0, v1End = 0, v2End = 0;
        
        //compare the value of each substring recognized by '.' character
    	while( v1End < size1 && v2End < size2 ){
            //get substring index
    		while( v1End < size1 && version1.charAt(v1End) != '.' )	++v1End;
    		while( v2End < size2 && version2.charAt(v2End) != '.' )	++v2End;
    
            //Absorb all the zeros at beginning
    		while( v1Start < size1 && version1.charAt(v1Start) == '0' )	++v1Start;
    		while( v2Start < size2 && version2.charAt(v2Start) == '0' )	++v2Start;
    
            //window size roughly tells the value
    		if( v1End-v1Start < v2End-v2Start ) return -1;
    		else if( v1End-v1Start > v2End-v2Start ) return 1;
    
            //compare its value digit by digit
    		while( v1Start < v1End && v2Start < v2End ){
    			if( version1.charAt(v1Start) < version2.charAt(v2Start) ) return -1;
    			else if( version1.charAt(v1Start) > version2.charAt(v2Start) ) return 1;
    			else{ ++v1Start; ++v2Start;	}
    		}
    		if( v1Start != v1End ) return -1;
    		if( v2Start != v2End ) return 1;
    
    		v1Start = ++v1End;
    		v2Start = ++v2End;
    	}
    
        //Absorb all the zeros at end and make comparison
    	if( v1End < size1 ){
    		while( v1End < size1 && (version1.charAt(v1End) == '0' || version1.charAt(v1End) == '.') )
    			++v1End;
    		if( v1End < size1 )	return 1;
    	}
    	if( v2End < size2 ){
    		while( v2End < size2 && (version2.charAt(v2End) == '0' || version2.charAt(v2End) == '.') )
    			++v2End;
    		if( v2End < size2 )	return -1;
    	}
    	return 0;
    }

Log in to reply
 

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