My C++ 2ms recursive method.


  • 0
    A

    My C++ by using recursive, 2ms. Pretty easy to understand, convert the integer part in the strings to int, and compare those two ints, if they are equal, using recursive, the next version is the sub string that from the "." to the end of the string.

    int compareVersion(string version1, string version2) {
            if(0 == version1.length() && 0 == version2.length()){
                return 0;
            }
            
            int v1 = 0;
            int v2 = 0;
            int i1 = 0;
            char temp = 0;
            
            while(i1 < version1.length() && '.' != (temp = version1.at(i1++))){
                v1 = 10 * v1 + (int)(temp - '0');
            }
            
            int i2 = 0;
            while(i2 < version2.length() && '.' != (temp = version2.at(i2++))){
                v2 = 10 * v2 + (int)(temp - '0');
            }
            
            if(v1 == v2){
                return compareVersion(version1.substr(i1), version2.substr(i2));
            }
            
            return v1 > v2 ? 1 : -1;
       }

Log in to reply
 

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