Accepted 3ms Java Solution


  • 0
    J
    public class Solution {
        public int compareVersion(String version1, String version2) {
            
            if(version1==null || version2==null || version1.length()<1 ||version2.length()<1) return 0;
            
            String[] v1Arr = version1.split("\\.");
            String[] v2Arr = version2.split("\\.");
            int v1Len = v1Arr.length;
            int v2Len = v2Arr.length;
            
            int len = Math.min(v1Arr.length,v2Arr.length);
            int i=0;
            for(i=0;i<len;i++){
                
                int v1 = Integer.valueOf(v1Arr[i]);
                int v2 = Integer.valueOf(v2Arr[i]);
                
                if(v1>v2) return 1;
                else if(v1<v2) return -1;
                
            }
            
            if(v1Len!=v2Len){
                
                String[] longerArr = (v1Len>v2Len) ? v1Arr : v2Arr;
                
                while(i<longerArr.length && Integer.valueOf(longerArr[i])==0) i++;
                
                if(i<longerArr.length) return (v1Len>v2Len)? 1 : -1;
            }
            
            return 0;
        }
    }
    

Log in to reply
 

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