Home Leetcode 165. Compare version number
Post
Cancel

Leetcode 165. Compare version number

Problem

Leet code problem 165
Difficulty: Medium

Solution

  1. Split each version into arrays of revisions using string.split(\\.)
    1
    2
    
     version1: 1.0.01 -> ["1", "0", "01"]
     version2: 1.0    -> ["1", "0"]
    
  2. Make sure the 2 arrays has the same size, the one has smaller size has to fill remaining with 0s logically
    1
    2
    3
    4
    
     version1: 1.0.01 -> ["1", "0", "01"] -> ["1", "0", "01"]
     version2: 1.0    -> ["1", "0"]       -> ["1", "0", "0"]
     Logically means v2.length = 2                       ^
     then consider index from 3 onward as 0
    
  3. For each item in both extracted arrays, compare and return accordingly
    1
    2
    3
    
     version1 > version2 ->  1
     version1 = version2 ->  0
     version1 < version2 -> -1
    

Implementation

Code from github

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class L165_CompareVersionNumbers {
  public int compareVersion(String version1, String version2) {
    String[] v1 = version1.split("\\.");
    String[] v2 = version2.split("\\.");

    int length = Math.max(v1.length, v2.length);
    for (int i = 0; i < length; i++) {
      int v1Revision = i >= v1.length ? 0 : Integer.valueOf(v1[i]);
      int v2Revision = i >= v2.length ? 0 : Integer.valueOf(v2[i]);

      if (v1Revision > v2Revision) {
        return 1;
      } else if (v1Revision < v2Revision) {
        return -1;
      }
    }
    return 0;

  }
}
This post is licensed under CC BY 4.0 by the author.