My Efficient Java Solution


  • 3
    S
    public class Solution {
    
        public int compareVersion(String version1, String version2) {
            String []num1 = version1.split("\\.");
            String []num2 = version2.split("\\.");
            int i=0,j=0;
            for (;i<=num1.length-1&&j<=num2.length-1;i++,j++)
                if (Integer.parseInt(num1[i])>Integer.parseInt(num2[j])) return 1;
                else if (Integer.parseInt(num1[i])<Integer.parseInt(num2[j])) return -1; 
            for(;i<=num1.length-1;i++) 
                if (Integer.parseInt(num1[i])!=0) return 1;
            for(;j<=num2.length-1;j++) 
                if (Integer.parseInt(num2[j])!=0) return -1;
            return 0;
    }
    }
    

    After splitting i checked if any of the digits in the head is greater than the other. If not then tries to remove trailing zeroes in versions . If the version number doesn't contain zeroes it returns the version number as highest.


  • 3
    S

    Thanks for your solution! Can you tell me, what is the difference between version1.split("."); and version1.split("\\.");?


  • 0
    K

    split() takes a regex, so split(".") splits on any character. The first backslash in "\." escapes the second backslash (for java string parsing) and the resulting single backslash escapes the . for the regex parser (telling it to treat the . as a literal period and not a representation of any character).


  • 0
    W

    Could you tell me what's the function of the last two for loop in more details? I don't understand your explanation. Thank you.


  • 0
    S

    Consider case1: 10.0 and 10.0.0.1.0.1 case2: 10.0 and 10.0.0.0.0.0. In case2 we need to go to the end of the version2 to make sure if version 1 and version2 are equal. As you can see in the case1 i go on iterating until i find any number other than 0. this is done by:
    if (Integer.parseInt(num1[i])!=0) return -1; .


  • 0
    W

    Yes, you're right. Thank you very much!


Log in to reply
 

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