165. Compare Version Numbers

Difficulty: Easy

Frequency: N/A

 

Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not “two and a half” or “half way to version three”, it is the fifth second-level revision of the second first-level revision.

Here is an example of version numbers ordering:

0.1 < 1.1 < 1.2 < 13.37

My solution:
Data structure:
string
Steps:
Complexity:
Runtime: O(n)
Space: O(1)
Test cases:
Corner cases:
1. “1”, “1.1”
2. “1.0.1”, “1”
3. “01”, “1”
Code:
class Solution {
public:
    int compareVersion(string version1, string version2) {
        for (; version1 != version2; version1 = get_substring(version1), version2 = get_substring(version2)) {
            if (stoi(version1) != stoi(version2)) return stoi(version1) > stoi(version2) ? 1 : -1;
        }
        return 0;
    }
    
    string get_substring(string v) {
        for (int i = 0; i < v.size(); i++) {
            if (v[i] == '.') return v.substr(i + 1);
        }
        return "0";
    }
};

Another solution:
Data structure:
steps:
Complexity:
Runtime:
Space:
Code:

Things to learn:
Advertisements

One thought on “165. Compare Version Numbers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s