【leetcode】165. Compare Version Numbers

本文详细阐述了如何将版本号字符串转换为整数数组,并通过比较整数数组来实现版本号之间的有效比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转换成int处理,由于存入vector,要处理容器匹配问题,

因此需要进行去除后缀0

</pre><pre name="code" class="cpp">/**
 *  @author         johnsondu
 *  @time           13:21 16th Oct 2015
 *  @status         Accepted
 *  @strategy       convert into integer to compare
 *  @problem        Compare Version Numbers
 *  @url            https://leetcode.com/problems/compare-version-numbers/
 */

class Solution {
public:
    int compareVersion(string version1, string version2) {
        vector<int> v1, v2, vv1, vv2;
        // convert into a series of numbers
        int idx = 0;
        while(idx < version1.size()) {
            int cur = 0;
            while(idx < version1.size() && version1[idx] != '.') {
                cur = cur * 10 + version1[idx] - '0';
                idx ++;
            }
            idx ++;
            v1.push_back(cur);
        }
        // in case of trail zeros
        idx = v1.size()-1;
        while(idx >= 0 && v1[idx] == 0) idx --;
        for(int i = 0; i <= idx; i ++) vv1.push_back(v1[i]);
        if(vv1.size() == 0) vv1.push_back(0);
    
        // convert into a series of numbers
        idx = 0;
        while(idx < version2.size()) {
            int cur = 0;
            while(idx < version2.size() && version2[idx] != '.') {
                cur = cur * 10 + version2[idx] - '0';
                idx ++;
            }
            idx ++;
            v2.push_back(cur);
        }
        // in case of trail zeros
        idx = v2.size() - 1;
        while(idx >= 0 && v2[idx] == 0) idx --;
        for(int i = 0; i <= idx; i ++) vv2.push_back(v2[i]);
        if(vv2.size() == 0) vv2.push_back(0);
        
        return (vv1 == vv2 ? 0 : (vv1 > vv2 ? 1 : -1));
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值