C++ 0m solution


  • 0

    Special cases:
    1 vs 1.0
    1 vs 1.0.2
    1.1 vs 1.1.1
    1 vs 1
    1 vs 2
    vice versa

    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            vector<int> v1;
            vector<int> v2;
    
            storeNumbers(v1, version1);
            storeNumbers(v2, version2);
            
            int i = 0;
            int j = 0;
            
            while(i < v1.size() && j < v2.size())
            {
                // version 1 > version 2
                if(v1[i] > v2[j])
                {
                    return 1;
                }
                else if(v2[j] > v1[i])
                {
                    return -1;
                }
                
                i++;
                j++;
            }
            
            // if there are leftover in version 1
            // EX: 1.1.2 > 1.1
            if(i < v1.size())
            {
                while(i< v1.size())
                {
                    if(v1[i] > 0)
                    {
                        return 1;
                    }
                    i++;
                }
                return 0;
            }
            else if(j < v2.size())
            {
                while(j < v2.size())
                {
                    if(v2[j] > 0)
                    {
                        return -1;
                    }
                    j++;
                }
                return 0;
            }
            else
            {
                return 0;
            }
        }
        
        void storeNumbers(vector<int>& holder, string& version)
        {
            int prevIndex = 0;
    
            // store each number in the string to vector
            for (int i = 0; i < version.length(); i++)
            {
                int currentNumber = 0;
    
                if (version[i] == '.')
                {
                    currentNumber = stoi(version.substr(prevIndex, i));
                    prevIndex = i + 1;
    
                    holder.push_back(currentNumber);
                }
                else if (i + 1 == version.length())
                {
                    string str = version.substr(prevIndex);
                    currentNumber = stoi(str);
                    holder.push_back(currentNumber);
                }
            }
        }
    };
    

Log in to reply
 

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