码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 165 Compare Version Numbers

时间:2016-05-16 14:23:32      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

题意:比较版本号的大小

有点变态,容易犯错

本质是字符串的比较,请注意他的版本号的小数点不知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;
    }
};

 

Leetcode 165 Compare Version Numbers

标签:

原文地址:http://www.cnblogs.com/onlyac/p/5497701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!