Easy solution in Java


  • 0
    D

    Consider some cases:

    1)"2.10000000000000000000000000000.0" "2.1"
    2)"001.0" "1"
    

    You can test your code with the cases above before uploading. Actually, some solutions showed in discuss fail to pass the cases above. Here is my solution:

    public int compareVersion(String version1, String version2) {
            String[] array1 = version1.split("\\.");
            String[] array2 = version2.split("\\.");
            int time = Math.max(array1.length, array2.length);
            for(int i = 0; i < time; i++) {
            	String s1 = i < array1.length ? array1[i] : "0";
            	String s2 = i < array2.length ? array2[i] : "0";
            	
            	int j = 0;
            	while(j < s1.length() - 1 && s1.charAt(j) == '0') j++;
            	if(j > 0) s1 = s1.substring(j);
            	j = 0;
            	while(j < s2.length() - 1 && s2.charAt(j) == '0') j++;
            	if(j > 0) s2 = s2.substring(j);
            	
                if(s1.length() == s2.length()) {
                    for(int k = 0; k < s1.length() ; k++) {
                        if(s1.charAt(k) == s2.charAt(k)) continue;
                        return s1.charAt(k) > s2.charAt(k) ? 1 : -1;                    
                    }
                }else{
                    return s1.length() > s2.length() ? 1 : -1;
                }
            }
            return 0;
        }
    

Log in to reply
 

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