LeetCode – Refresh – Compare Version Numbers

本文介绍了一种使用C++实现的版本号比较算法,该算法通过将版本号字符串分割为各个部分并进行逐段数值比较来确定两个版本号之间的大小关系。文章提供了具体的C++代码实现细节。

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

Two notes:

1. I dont know whether C++ has a good split function for STL as the JAVA. Need to figure it out.

2. At the beginning, I tried to set tmp1 = tmp2 = INT_MIN. But one of test case does not work "1.0" and "1". So those two does not need to set be INT_MIN or INT_MAX every time. It should be 0 at this time.

 1 class Solution {
 2 public:
 3     vector<string> splits(string s) {
 4         vector<string> result;
 5         int len = s.size();
 6         for (int i = len-1; i >= 0; i--) {
 7             if (s[i] == '.') {
 8                 len = i;
 9             } else if (i == 0 || s[i-1] == '.') {
10                 result.push_back(s.substr(i, len - i));
11             }
12         }
13         return result;
14     }
15     int compareVersion(string version1, string version2) {
16         if (version1.size() == 0 && version2.size() == 0) return 0;
17         if (version1.size() == 0) return -1;
18         if (version2.size() == 0) return 1;
19         vector<string> list1 = splits(version1);
20         vector<string> list2 = splits(version2);
21         int l1 = list1.size()-1, l2 = list2.size()-1;
22         while (l1 >= 0 || l2 >= 0) {
23             int tmp1 = 0, tmp2 = 0;
24             if (l1 >= 0) {
25                 tmp1 = stoi(list1[l1--]);
26             }
27             if (l2 >= 0) {
28                 tmp2 = stoi(list2[l2--]);
29             }
30             if (tmp1 > tmp2) return 1;
31             else if (tmp1 < tmp2) return -1;
32         }
33         return 0;
34     }
35 };

 

转载于:https://www.cnblogs.com/shuashuashua/p/4349274.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值