Simple recursive solution with C++


  • 0
    S
    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            auto idot1 = version1.find('.');
            auto idot2 = version2.find('.');
            // First compare the string before "."
            if (stoi(version1.substr(0, idot1)) > stoi(version2.substr(0,idot2))) {
                return 1; // Note: this program won't be robust against empty strings, because stoi() won't accept empty string.
            }
            else if (stoi(version1.substr(0, idot1)) < stoi(version2.substr(0,idot2))) {
                return -1;
            }
            else { // If they are equivalent, compare the string after "."
                if (idot1 == string::npos && idot2 == string::npos) 
                    return 0;   // If there were no ".", we reach conclusion
                else if (idot1 == string::npos) // If version1 contains no ".", replace it with "0" and compare the following string
                    return compareVersion("0", version2.substr(idot2+1));
                else if (idot2 == string::npos) 
                    return compareVersion(version1.substr(idot1+1), "0");
                else 
                    return compareVersion(version1.substr(idot1+1), version2.substr(idot2+1));
            }
        }
    };
    

Log in to reply
 

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