
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.
1public class CompareVersion {
2 public int compareVersion(String version1, String version2) {
3 String[] v1 = version1.split("\\.");
4 String[] v2 = version2.split("\\.");
5
6 int length = Math.max(v1.length, v2.length);
7 for (int i = 0; i < length; i++) {
8 int num1 = i < v1.length ? Integer.parseInt(v1[i]) : 0;
9 int num2 = i < v2.length ? Integer.parseInt(v2[i]) : 0;
10 if (num1 < num2) return -1;
11 if (num1 > num2) return 1;
12 }
13
14 return 0;
15 }
16}This Java solution involves splitting the version strings with split method into arrays. An iteration through the arrays converts each component into integers for comparison. If unequal, -1 or 1 is returned, otherwise the loop continues.
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
The C solution employs a method where pointers traverse each version string, constructing numerical values between dots manually. This avoids unnecessary string operations and directly compares values to determine the result.