Very concise Java solution

  • 0
    public class Solution {
    public int compareVersion(String version1, String version2) {
        if(version1=="") return version2==""?0:-1;
        if(version2=="") return 1;
        String[] v1 = version1.split("\\.");
        String[] v2 = version2.split("\\.");
        int n = Math.max(v1.length,v2.length);
        for(int i=0,first=0,second=0;i<n;i++,first=0,second=0){//mind the default value 0
            if(i<v1.length) first = Integer.parseInt(v1[i]);//when i is larger than its length, the default value is 0
            if(i<v2.length) second = Integer.parseInt(v2[i]);
            if(first<second) return -1;
            else if(first>second) return 1;
        return 0;


Log in to reply

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