• 【leetcode 字符串处理】Compare Version Numbers


    【leetcode 字符串处理】Compare Version Numbers


    @author:wepon
    @blog:http://blog.csdn.net/u012162613

    1、题目

    Compare two version numbers version1 and version1.
    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

    2、分析

    题意:题意非常清晰。就是比較“版本”大小。给定的版本version1和version2是字符串类型的。当version1>version2的时候。返回1。反之返回-1。


    这道题属于细节处理题,除了字符串处理繁琐一点之外没有什么。

    解题思路:先分别将version1、version2字符串按'.'切割成多个子串,每一个子串转化成整型存入容器。

    最后再比較两个容器中相应位置的数的大小。

    当然须要考虑它们长度不同的情况。


    注意点:
    (1)version的形式:10.23.1、01.23、1.2.3.4....诸如此类
    (2)字符串转化成整型,我的程序中直接用库函数stoi()

    3、代码

    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            vector<int> result1=getInt(version1);
            vector<int> result2=getInt(version2);
            int len1=result1.size();
            int len2=result2.size();
            if(len2<len1) return -1*compareVersion(version2, version1);
            int i=0;
            while(i<len1 && result1[i]==result2[i]) i++;
            
            if(i==len1){    //str1和str2前len1位都相等,则看看str2后面的len2-len1位是否都为0就可以推断它们的大小
                int j=len2-1;
                while(j >= len1){
                    if(result2[j--]!=0) return  -1;
                }
                return 0;
            }else{       //str1和str2前len1位不都相等。直接推断第i位
                if(result1[i]<result2[i]) return -1;
                else return 1;
            }
        }
    private:
    //将version字符串按'.'拆成多个。转化为整型放入容器
        vector<int> getInt(string version){
            vector<int> result;
            int len=version.size();
            int pre=0;
            for(int i=0;i<len;i++){
                if(version[i]=='.'){
                    string str(version.begin()+pre,version.begin()+i);  //注意这样的初始化形式,左闭右开,即str不包含version[version.begin()+i]
                    result.push_back(stoi(str));
                    pre=i+1;
                }
            }
    		string str(version.begin()+pre,version.end());
            result.push_back(stoi(str));
            return result;
        }
    };


  • 相关阅读:
    第四季-专题8-Linux系统调用
    第四季-专题7-Linux内核链表
    Python3 运算符
    Python2和Python3有什么区别?
    python常见的PEP8规范
    机器码和字节码
    域名是什么?为什么域名是www开头?
    selenium自动化登录qq邮箱
    xpath+selenium工具爬取腾讯招聘全球岗位需求
    ArrayList
  • 原文地址:https://www.cnblogs.com/llguanli/p/6994255.html
Copyright © 2020-2023  润新知