1ms Java Solution


  • 0
    B
    public class Solution {
        public int compareVersion(String version1, String version2) {
            
            int start1 = 0;
            int start2 = 0;
            
            while(start1 < version1.length() || start2 < version2.length()){
                
                int v1end = version1.indexOf('.', start1) != -1? version1.indexOf('.',start1) : version1.length();
                int v2end = version2.indexOf('.', start2) != -1? version2.indexOf('.',start2) : version2.length();
                int comp = 0;
                
                if(start1 >= version1.length()){
                    comp = compareVersion_intern("0", version2.substring(start2, v2end));
                }else if(start2 >= version2.length()){
                    comp = compareVersion_intern(version1.substring(start1, v1end), "0");
                }else{
                    comp = compareVersion_intern(version1.substring(start1, v1end), version2.substring(start2, v2end));
                }
                
                if(comp != 0){
                    return comp;
                }else{
                    start1 = v1end + 1;
                    start2 = v2end + 1;
                }
            }
            return 0;
        }
        
        private int compareVersion_intern(String version1, String version2){
            int v1 = 0;
            int v2 = 0;
            int factor = 1;
            for(int i = version1.length()-1; i >= 0; i--){
                v1 += (version1.charAt(i) - '0')*factor;
                factor *= 10;
            }
            factor=1;
            for(int i = version2.length()-1; i >= 0; i--){
                v2 += (version2.charAt(i) - '0')*factor;
                factor *= 10;
            }
            
            if(v1 > v2){
                return 1;
            }else if(v1 < v2){
                return -1;
            }else{
                return 0;
            }
        }
    }

Log in to reply
 

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