LeetCode 165. Compare Version Numbers

本文详细解读了LeetCode中版本号比较算法的实现,包括如何使用split方法拆分字符串,以及通过Integer.valueOf()将拆分后的字符串转换为整数进行比较。详细介绍了算法的时间复杂性和空间复杂性。

原题链接在这里: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值