码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Compare Version Numbers

时间:2015-01-27 07:03:31      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

Compare two version numbers version1 and version1.
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

这道题的意思用一个例子说明就是1.2 < 1.10, 因为1.10跟1.1是不一样的,1.10代表tenth revision. 而1.1代表first revision。所以这道题要按“.”分段,然后分段比较,方法是用split函数把string 分段,每一段挨个比过去。这里参考了网上的一个小技巧:

由于两串字符串并不是一样长度的,如果分情况比较,如第一个长,遍历逐一比较则要分情况讨论。此时就采取一些小技巧,将两个字符串对齐,就无需考虑各种情况,超出的位数补0即可,这是一种字符串、数串比较的小技巧。

所以这里取了两个string长度的最大值 maxLen, 来建立两个数组来存split“.”之后分出来的数字,短的那个数组末尾默认补0. 然后从左到右挨个比过去

Integer.parseInt()函数能将“012”转化为12,解决了首位为0的问题

另外用split函数有一点特别要注意:我们知道,“ . ”在正则表达式中有特殊的含义,因此我们使用的时候必须进行转义。

不转义就会有如下结果:

String ipstring="59.64.159.224";  

String iparray[]=ipstring.split(".");  

for(String stemp:iparray){  

System.out.println(stemp);  

}  

这个输出为空,为什么呢?  

public string[] split(string regex) 这里的参数的名称是regex ,也就是 regular expression (正则表达式)。

“ . ”在正则表达式中有特殊的含义,表示means "any character" in regex

所以如果就想表示一个点的话,use either split("\\.") or split(Pattern.quote(".")).

 1 public class Solution {
 2     public int compareVersion(String version1, String version2) {
 3         String[] strs1 = version1.split("\\.");
 4         String[] strs2 = version2.split("\\.");
 5         int maxLen = Math.max(strs1.length, strs2.length);
 6         int[] nums1 = new int[maxLen];
 7         int[] nums2 = new int[maxLen];
 8         for (int i=0; i<strs1.length; i++) {
 9             nums1[i] = Integer.parseInt(strs1[i]);
10         }
11         for (int i=0; i<strs2.length; i++) {
12             nums2[i] = Integer.parseInt(strs2[i]);
13         }
14         for (int i=0; i<maxLen; i++) {
15             if (nums1[i] > nums2[i]) return 1;
16             else if (nums1[i] < nums2[i]) return -1;
17         }
18         return 0;
19     }
20 }

 

Leetcode: Compare Version Numbers

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/4251818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!