zoukankan      html  css  js  c++  java
  • [leet code 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

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

    2 思路

    好吧,这题很蛋疼,各种情况。有1.0与1比较的,有1.2.3与1.2比较的,考虑到各种情况,很复杂。还发现java里面split函数输入是正则表达式,要用"."符号分割的话,得这样.split"\.",才能分割。

    网上查了查,有一个思路是用递归解决的,http://www.tuicool.com/articles/3QV7NvV。完美解决 比较 1.0与1的问题。

    我感觉实际操作中,会规定死版本的格式吧。如1.2.3与1.0.0。另外,我看实际中的一个代码,只要发现两个版本的字符串不一样,就提醒用户更新版本- -。

    3 代码

        public int compareVersion(String version1, String version2) {    
            if(version1.equals(version2))
                return 0;
            int fversion1 , fversion2;//最左边字符串代表的数字
            String sversion1,sversion2;//剔除.号左边的数字剩下的字符串
            if(version1.contains(".")){
                int pos = version1.indexOf(".");
                fversion1 = Integer.valueOf(version1.substring(0,pos));
                sversion1 = version1.substring(pos+1,version1.length());
            }else {
                fversion1 = Integer.valueOf(version1);
                sversion1 = "0";//预防比较1.0与1这种情况
            }
            if(version2.contains(".")){
                int pos = version2.indexOf(".");
                fversion2 = Integer.valueOf(version2.substring(0,pos));
                sversion2 = version2.substring(pos+1,version2.length());
            }else {
                fversion2 = Integer.valueOf(version2);
                sversion2 = "0";
            }
            if(fversion1 > fversion2)
                return 1;
            else if(fversion1 < fversion2)
                return -1;
            else return compareVersion(sversion1, sversion2);
        }
        
  • 相关阅读:
    C++ list<list<int> >类型的对象遍历
    Apache与Nginx服务器对比
    服务器重写技术:rewrite
    冒泡排序(python版)
    有k个list列表, 各个list列表的元素是有序的,将这k个列表元素进行排序( 基于堆排序的K路归并排序)
    堆排序(C++版)
    [转载] 单链表的相关操作
    TCP三次握手连接与四次握手断开
    [转载] TCP与UDP对比
    进程与线程的联系与区别
  • 原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4314352.html
Copyright © 2011-2022 走看看