165. Compare Version Numbers

Description

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.

Example 1:

Input: *version1* = "0.1", *version2* = "1.1"
Output: -1

Example 2:

Input: *version1* = "1.0.1", *version2* = "1"
Output: 1

Example 3:

Input: *version1* = "7.5.2.4", *version2* = "7.5.3"
Output: -1

Solution

Iteration, time O(n), space O(n)

题意很明白。首先将version按照"." split开,然后逐位比较大小即可。

需要注意的是:

  • string#split(String regex)里面的参数是regex,对于'.'需要做转译,否则会返回空数组(大坑)。参考:Java中的split函数的用法
  • 对于这种test case: "1.0", "1",要返回相等
class Solution {
    public int compareVersion(String version1, String version2) {
        String[] arr1 = version1.split("\\.");  // use regex!
        String[] arr2 = version2.split("\\.");
        int len1 = arr1.length;
        int len2 = arr2.length;
        
        for (int i = 0; i < Math.max(len1, len2); ++i) {
            int val1 = i < len1 ? Integer.parseInt(arr1[i]) : 0;
            int val2 = i < len2 ? Integer.parseInt(arr2[i]) : 0;
            
            if (val1 != val2) {
                return Integer.compare(val1, val2);
            }
        }
        
        return 0;
    }
}

你可能感兴趣的:(165. Compare Version Numbers)