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

Leetcode Compare Version Numbers

时间:2015-09-22 10:04:15      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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

解题思路:

常规思路,用split()分割string, IMPORTANT : Some special characters need to be escaped while providing them a delimiters like "." and "\".

然后用Integer.parseInt(x)转换成int 比较大小。注意: 1.0 和1 相等,因此判断还剩一个string 的时候,值要不等于0 才大于另一个string.

题目不难,但容易错,要小心仔细。


 Java code:

public int compareVersion(String version1, String version2) {
        String delimiter = "\\.";
        String[] v1 = version1.split(delimiter);
        String[] v2 = version2.split(delimiter);
        int len = Math.max(v1.length, v2.length);
        for(int i = 0; i< len; i++){
            if(i < v1.length && i < v2.length){
                if(Integer.parseInt(v1[i]) > Integer.parseInt(v2[i])) {
                    return 1;
                }else if(Integer.parseInt(v1[i]) < Integer.parseInt(v2[i])){
                    return -1;
                }
            }else if(i < v1.length) {
                if(Integer.parseInt(v1[i]) > 0) {
                    return 1;
                }
            }else if(i < v2.length){
                if(Integer.parseInt(v2[i]) > 0) {
                    return -1;
                }
            }
        }
        return 0;
    }

Reference:

1. http://www.programcreek.com/2014/03/leetcode-compare-version-numbers-java/

 

Leetcode Compare Version Numbers

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4827951.html

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