Java recursive solution


  • 0
    C
    public class Solution {
    public int compareVersion(String v1, String v2) {
    int v1L = 0,  v2L = 0, i = 0, j = 0;
    	while( i < v1.length() && v1.charAt(i) != '.')
    	{
    			v1L = 10*v1L + (int)(v1.charAt(i++) - '0');  	
    	}
    	while(j < v2.length() && v2.charAt(j) != '.')
    	{
    			v2L = 10*v2L + (int)(v2.charAt(j++) - '0');  	
    	}
    	if (v1L < v2L)
    		return -1;
    	else if (v1L > v2L)
    		return 1;
        else // current level equals, compare next level
    	{
            if (i+1 > v1.length() && j+1 > v2.length())
                return 0;
            else
            {
    		  String t1 = new String(v1.substring(Math.min(i+1,v1.length()),v1.length())); // min is to handle corner cases
    		  String t2 = new String(v2.substring(Math.min(j+1,v2.length()),v2.length()));
    		  return compareVersion(t1,t2);
            }
    	}
    }
    }

Log in to reply
 

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