LeetCode 165 Compare Version Numbers

来源:互联网 发布:淘宝活动文案范文 编辑:程序博客网 时间:2024/05/16 09:50

题目描述

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

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

分析

比较字符串版本号大小。

  1. 把字符串按照’.’分隔成字符串数组v1,v2

  2. 因为字符串数组v1,v2的长度可能不一样,要前端对齐,较短的字符串数组变长,后面为null

  3. 分别对每一个数进行比较


本来以为这道题会有,字符串转成int溢出的问题,结果没考虑这个问题也AC了~ ^_^

代码

    public static int compareVersion(String version1, String version2) {        String[] v1 = version1.split("\\.");        String[] v2 = version2.split("\\.");        int m = Math.max(v1.length, v2.length);        v1 = Arrays.copyOf(v1, m);        v2 = Arrays.copyOf(v2, m);        for (int i = 0; i < m; i++) {            int n1 = 0;            int n2 = 0;            if (v1[i] != null) {                n1 = Integer.valueOf(v1[i]);            }            if (v2[i] != null) {                n2 = Integer.valueOf(v2[i]);            }            if (n1 < n2) {                return -1;            } else if (n1 > n2) {                return 1;            }        }        return 0;    }
1 0
原创粉丝点击