Leetcode 165 Solution

This article provides solution to leetcode question 165 (compare-version-numbers).

https://leetcode.com/problems/compare-version-numbers

Solution

class Solution {
public:
    void split_version(string version, vector<int>& v)
    {
        int cur_pos = 0;
        do
        {
            auto next_pos = version.find_first_of('.', cur_pos);
            
            if (next_pos != string::npos)
            {
                v.push_back(stoi(version.substr(cur_pos, next_pos - cur_pos)));
                cur_pos = next_pos + 1;
            }
            else
            {
                v.push_back(stoi(version.substr(cur_pos)));
                cur_pos = next_pos;
            }
            
        } while (cur_pos != string::npos);
    }
    
    int compareVersion(string version1, string version2) {
        vector<int> v1, v2;
        split_version(version1, v1);
        split_version(version2, v2);
        
        auto it1 = v1.begin();
        auto it2 = v2.begin();
        
        while (it1 != v1.end() || it2 != v2.end())
        {
            if (it1 != v1.end() && it2 != v2.end())
            {
                if (*it1 > *it2)
                    return 1;
                else if (*it1 < *it2)
                    return -1;
            }
            else if (it1 != v1.end() && *it1 != 0)
            {
                return 1;
            }
            else if (it2 != v2.end() && *it2 != 0)
            {
                return -1;
            }
            
            if (it1 != v1.end()) it1++;
            if (it2 != v2.end()) it2++;
        }
        
        return 0;
    }
};