
Sponsored
Sponsored
This approach involves splitting the version strings into individual components using the dot delimiter. We then convert these components into integers and compare them one by one. If one version string is shorter, we treat the missing components as 0, allowing a fair comparison.
Time Complexity: O(n + m), where n and m are lengths of version1 and version2 respectively.
Space Complexity: O(n + m) for holding the split components.
1#include <iostream>
2#include <vector>
3#include <sstream>
4
5using namespace std;
6
7int compareVersion(string version1, string version2) {
8 istringstream v1(version1), v2(version2);
9 string num1, num2;
10 while (getline(v1, num1, '.') || getline(v2, num2, '.')) {
11 int n1 = num1.empty() ? 0 : stoi(num1);
12 int n2 = num2.empty() ? 0 : stoi(num2);
13 if (n1 < n2) return -1;
14 if (n1 > n2) return 1;
15 num1.clear();
16 num2.clear();
17 }
18 return 0;
19}The C++ solution leverages istringstream to extract components separated by dots. Components are converted to integers using stoi. We compare each integer and return -1 or 1 if they are unequal, continuing until all components are processed.
This approach utilizes two pointers to traverse each version string's components simultaneously. By identifying and isolating numerical values between dots without splitting the string, we optimize for memory usage. Each number is evaluated and compared until a determination is made or the end is reached.
Time Complexity: O(n + m), where n and m are the lengths of version1 and version2.
Space Complexity: O(1), as no significant additional space is used.
1
Using index navigation, this Java solution creates each numerical component by parsing strings character by character to avoid typical string handling overhead, promoting efficient comparison.