• Leetcode 165 Compare Version Numbers


    题意:比较版本号的大小

    有点变态,容易犯错

    本质是字符串的比较,请注意他的版本号的小数点不知1个,有的会出现01.0.01这样的变态版本号

    class Solution {
    public:
        int cmp_num(string a, string b){
            if(a.size() < b.size()) return -1;
            else if(a.size() == b.size()){
                if(a == b) return 0;
                else return a < b ? -1:1 ;
            }
            else return 1;
        }
        vector<string> change(string v){
            vector<string> vs;
            int a = 0, b = 0;
            while((b = v.find(".",a)) != string::npos){
                string::size_type i = a;
                for(; i < v.size(); ++i){
                    if(v[i] > '0' || v[i] == '.') break;
                }
                if(i == v.size() || v[i] == '.') vs.push_back("0");
                else vs.push_back(v.substr(i, b- i));
                a = b + 1;
            }
            string::size_type i = a;
            for(; i < v.size(); ++i){
                if(v[i] > '0' || v[i] == '.') break;
            }
            if(i == v.size() || v[i] == '.') vs.push_back("0");
            else vs.push_back(v.substr(i,  v.size() - i));
            return vs;
        }
        int compareVersion(string version1, string version2) {
            vector<string> v1,v2;
            v1 = change(version1);
            v2 = change(version2);
            
            string::size_type i;
            for(i = 0; i < v1.size() && i <v2.size(); ++i){
                if(cmp_num(v1[i],v2[i]) != 0) return cmp_num(v1[i],v2[i]);
            }
            
            for(; i < v1.size(); ++i){
                if(cmp_num(v1[i],"0") != 0) return cmp_num(v1[i],"0");
            }
            
            for(; i < v2.size(); ++i){
                if(cmp_num("0",v2[i]) != 0) return cmp_num("0",v2[i]);
            }
            
            return 0;
        }
    };
  • 相关阅读:
    Extension Methods(扩展方法)
    linux面试题
    渗透测试 day4
    渗透测试 day3
    渗透测试 day2
    渗透测试 day1
    9.3 网络安全介绍
    9.2 Iptables
    8.30 进程管理
    8.29 linux的网络
  • 原文地址:https://www.cnblogs.com/onlyac/p/5497701.html
Copyright © 2020-2023  润新知