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 < 1.13 < 1.13.4
Method:
Be careful of the case of comparing 1.0.0 and 1, it should return 0.
Solution:
Time: O(m + n) Space: O(m + n)
import java.math.BigInteger;
public class Solution { public int compareVersion(String A, String B) { String[] a = A.split("\\."); String[] b = B.split("\\."); int len = Math.min(a.length, b.length); for (int i = 0; i < len; i ++) { BigInteger aVal = new BigInteger(a[i]); BigInteger bVal = new BigInteger(b[i]); int compare = aVal.compareTo(bVal); if (compare != 0) { return compare; } } if (a.length < b.length) { for (int i = len; i < b.length; i ++) { BigInteger bVal = new BigInteger(b[i]); if (!bVal.equals(BigInteger.ZERO)) { return -1; } } return 0; } else if (a.length > b.length) { for (int i = len; i < a.length; i ++) { BigInteger aVal = new BigInteger(a[i]); if (!aVal.equals(BigInteger.ZERO)) { return -1; } } return 0; } else { return 0; } } }