My accepted Java solution


  • 0
    Y
    public class CompareVersion {
       public int compareVersion(String version1, String version2) {
    	String[] list1 = version1.split("\\.");
    	String[] list2 = version2.split("\\.");
    	
    	int length = Math.min(list1.length, list2.length);
    	
    	for (int i = 0; i < length; i++) {
    		if (Integer.valueOf(list1[i]) > Integer.valueOf(list2[i])) return 1;
    		if (Integer.valueOf(list1[i]) < Integer.valueOf(list2[i])) return -1;
    	}
    	if (list1.length > length) {
    		if (Integer.valueOf(list1[length]) > 0) return 1;
    	}
    	if (list2.length > length) {
    		if (Integer.valueOf(list2[length]) > 0) return -1;
    	}
    	return 0;
    }

  • 0
    D

    Looks good for most case but I am thinking about one case:

    version1: 0.0.0.0.0.0.0.0.1
    version2: 0

    It seems like it will return 0 which we expect is 1. Please correct me if I am wrong.


  • 0
    T

    last part can be replaced like this example:
    int index = lenth;
    while(index<str1.length){
    if (Integer.valueOf(str1[index++]) > 0) return 1;
    }


Log in to reply
 

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