Sharing my 0ms C++ solution


  • 0
    T
    class Solution {
    private:
        vector<int> convert(string version)
        {
            vector<int> result;
            int n = version.length();
            int start = 0;
            for(int i=0; i<n; i++)
            {
                if(version[i]=='.')
                {
                    string s = version.substr(start, i-start);
                    start = i+1;
                    result.push_back(atoi(s.c_str()));
                }
            }
            if(start<n)
            {
                string str = version.substr(start, n-start);
                result.push_back(atoi(str.c_str()));
            }
            
            while(result.size()>0 && result.back()==0)
            {
                result.pop_back();
            }
            
            return result;
        }
        
        int compareVersionHelper(vector<int>& v1, vector<int>& v2, int pos)
        {
            if(pos==v1.size() && pos==v2.size())
                return 0;
            else if(pos==v1.size())
                return -1;
            else if(pos==v2.size())
                return 1;
            else if(v1[pos]<v2[pos])
                return -1;
            else if(v1[pos]>v2[pos])
                return 1;
            else
                return compareVersionHelper(v1, v2, pos+1);
        }
        
    public:
        int compareVersion(string version1, string version2) {
            vector<int> v1 = convert(version1);
            vector<int> v2 = convert(version2);
            return compareVersionHelper(v1, v2, 0);
        }
    };

Log in to reply
 

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