• Leetcode 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

    解题思路:

    常规思路,用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/

  • 相关阅读:
    WPF Web Application 客户端下载目录及有趣的搜索问题
    判断表是否存在
    C#获取存储过程返回值和输出参数值
    模态对话框刷新问题
    sql Server 导出数据到脚本
    使用.NET 2.0中的秒表-Stopwatch类进行速度测试 (转一个程序员的自省)
    使用Redirect打开新窗口
    弹出层
    windows7安装配置IIS7.5过程图解
    控制文本框输入
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4827951.html
Copyright © 2020-2023  润新知