[165] Compare Version Numbers

1. 题目描述

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

给定两个使用“.”分割的版本号,实现comparable接口(相当于)。

2. 解题思路

首先给定两个版本号,那么什么情况下版本号a.b.c大于版本号d.e呢,那么就是哪个在前的数字大哪个版本号就大,考虑两个版本号,首先将字符串进行分割,之后将分割的字符串转换为数字。一直比较到长度比较短的版本号结束,这时,如果前面有大小的区分,就已经有结果了,如果比较到短的串的最后一位还没有结果,那么看比较长的串后面是不是全0,当前Code是将String转换为了int,后来觉得是不是判断一下是不是equals(“0”)就好,但是事实证明变态的测试用例不是这样玩的,测试用例给定的版本号不一定是一个正常的数字,有可能是01,000之类的串,所以目前想到的就是转换成int啦。

3. Code

public class Solution {
    public int compareVersion(String version1, String version2) {
        // 将String分割为若干字符串
        String[] v1 = version1.split("\\.");
        String[] v2 = version2.split("\\.");
        for(int i = 0; i < Math.min(v1.length, v2.length); ++i)
        {
            // 将String解析为int
            int num1 = Integer.parseInt(v1[i]);
            int num2 = Integer.parseInt(v2[i]);
            // 如果两个值不相等,v1>v2返回1,否则返回-1
            if(num1 != num2) return num1 > num2 ? 1 : -1;
        }
        // 如果两个串长度相等,返回相等
        if(v1.length == v2.length) return 0;
        // 如果长度不等,长度长的那个大(×) 有可能是a.b.c.0.0.00.0
        for(int j = Math.min(v1.length, v2.length); j < Math.max(v1.length, v2.length); ++j)
        {
            if(v1.length > v2.length)
            {
                int num = Integer.parseInt(v1[j]);
                if(num != 0) return 1;
            }
            else if(v2.length > v1.length)
            {
                int num = Integer.parseInt(v2[j]);
                if(num != 0) return -1;
            }
        }
        return 0;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章