
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 Solution {
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 ? int.Parse(v1[i]) : 0;
9 int num2 = i < v2.Length ? int.Parse(v2[i]) : 0;
10 if (num1 < num2) return -1;
11 if (num1 > num2) return 1;
12 }
13
14 return 0;
15 }
16}The C# solution employs the Split method to separate version strings into components. Each segment is parsed into integers for comparison within a loop.
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.