4ms, 22 lines solution using c++11


  • 0
    S
    class Solution {
    public:
    int compareVersion( const string &version1, const string &version2 ) {
        std::size_t index1, index2;
        int num1 = std::stoi( version1, &index1 );
        int num2 = std::stoi( version2, &index2 );
        if( num1 != num2 ) {
            return num1 > num2 ? 1 : -1;
        } else {
            if( index1 == version1.size() && index2 == version2.size() ) {
                return 0;
            }
            string str1 = "0", str2 = "0";
            if( index1 != version1.size() ) {
                str1 = version1.substr( index1 + 1 );
            }
            if( index2 != version2.size() ) {
                str2 = version2.substr( index2 + 1 );
            }
            return compareVersion( str1, str2 );
        }
     } };

Log in to reply
 

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