Compare Version Numbers

本文介绍了一种用于比较软件版本号的算法实现。通过使用C++和stringstream处理版本号字符串,将其转换为整数序列以便比较。文章详细解释了处理过程,并提供了一个完整的代码示例。

题目名称
Compare Version Numbers—LeetCode链接

描述
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

分析
  题目中并没有说明版本号只有1.1,1.2这种类型,还有1.2.3,1.2.3.4等都是版本号。而且在比较的过程中,1.1也可以和1.1.2比较。
  一个简单的方法就是将两个字符串按照“.”分割后分别存储到两个vector中,如果vector的大小不一样,则对小的进行扩充,使两个vector大小相等,然后遍历两个vector,进行比较。

C++代码

class Solution {
public:
    vector<int> convert(string& s){
        stringstream ss;
        vector<int> res;
        s+=".";
        int j;
        int size=s.size();
        for(int i=0;i<size;i++){
            //这一步非常重要,防止ss复用
            ss.clear();
            //寻找i之后第一次出现“.”的位置
            j = s.find(".",i);
            string sub = s.substr(i,j-i);
            //清空缓冲区
            ss.str("");
            ss.str(sub);
            int num;
            ss >> num;
            res.push_back(num);
            i=j;
        }
        return res;
    }

    int compareVersion(string version1, string version2) {
        vector<int> v1 = convert(version1);
        vector<int> v2 = convert(version2);
        int maxSize = (v1.size()>v2.size())?v1.size():v2.size();
        v1.resize(maxSize);
        v2.resize(maxSize);

        for(int i=0;i<maxSize;i++){
            if(v1[i]>v2[i])
                return 1;
            else if(v1[i]<v2[i])
                return -1;
        }
        return 0;
    }
};

总结
  C++中涉及到数据类型转换时,用stringstream最方便了。在解决这道题时,因为一开始没有对字符串流进行clear()操作,导致了第一次出现的值一直被复用,从这道题中我也学到了很多,之后我会写一篇用stringstream进行数据转换的文章。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值