LeetCode 165. Compare Version Numbers

原题链接在这里:https://leetcode.com/problems/compare-version-numbers/

题目:

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 < 13.37

题解:

用string.split()方法把原有string 从小数点拆成 string 数组,但这里要注意 . 和 * 是不能直接用split(".") 或者split("*")拆开的,因为 . 可以代表任意char, * 可以代表任意字符串。所以要加 \. 来避免individual special character.

拆开后用Interger.valueOf()转换成数字直接比较就好。

拆完后两个数组长度可能不同, "1" 和 "1.1", 所以while 循环的条件是i < ver1.length 或者 i<ver2.length.

Time Complexity: O(Math.max(version1.length, version2.length)), 因为用了split.

Space: O(version1.length + version2.length), 建立了array.

AC Java:

 1 class Solution {
 2     public int compareVersion(String version1, String version2) {
 3         if(version1 == null || version2 == null){
 4             throw new IllegalArgumentException("Invalid input string.");
 5         }
 6         
 7         String [] v1 = version1.split("\.");
 8         String [] v2 = version2.split("\.");
 9         
10         int i = 0;
11         while(i<v1.length || i<v2.length){
12             int a = i<v1.length ? Integer.valueOf(v1[i]) : 0;
13             int b = i<v2.length ? Integer.valueOf(v2[i]) : 0;
14             if(a < b){
15                 return -1;
16             }else if(a > b){
17                 return 1;
18             }
19             
20             i++;
21         }
22         return 0;
23     }
24 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824938.html