[LeetCode] Compare Version Numbers

本文介绍了一种使用C++来比较软件版本号的方法。通过将版本号分解为数字并逐位对比,实现了不同长度版本号的有效比较。文中提供了两种实现方式,一种是手动分割版本号字符串,另一种利用了stringstream和getline函数。

The idea is very simple: just extract the numbers from each version number and compare the numbers from beginning to the end. However, C++ seems to have no split functions like those of Java and Python. So we need to split it by our code. A final note, remember to handle version numbers of different lengths.

The code is as follows.

 1 class Solution {
 2 public:
 3     int compareVersion(string version1, string version2) {
 4         vector<int> v1 = version(version1);
 5         vector<int> v2 = version(version2);
 6         int m = v1.size(), n = v2.size(), i, j;
 7         for (i = 0, j = 0; i < m && j < n; i++, j++)
 8             if (v1[i] > v2[j]) return 1;
 9             else if (v1[i] < v2[j]) return -1;
10         while (i < m && v1[i++]) return 1;
11         while (j < n && v2[j++]) return -1;
12         return 0;
13     }
14 private:
15     vector<int> version(string& version) {
16         int n = version.length();
17         string vs;
18         vector<int> v;
19         for (int i = 0; i <= n; i++) {
20             if (i == n || version[i] == '.') { 
21                 v.push_back(stoi(vs));
22                 vs.clear();
23                 if (i == n) break;
24             }
25             else vs += version[i];
26         }
27         return v;
28     }
29 };

These two lines in the above handle the case of version numbers with different lengths.

1 while (i < m && v1[i++]) return 1;
2 while (j < n && v2[j++]) return -1; 

We may also implement version using some system functions like stringstream and getline.

 1 class Solution {
 2 public:
 3     int compareVersion(string version1, string version2) {
 4         vector<int> v1 = version(version1);
 5         vector<int> v2 = version(version2);
 6         int m = v1.size(), n = v2.size(), i, j;
 7         for (i = 0, j = 0; i < m && j < n; i++, j++)
 8             if (v1[i] > v2[j]) return 1;
 9             else if (v1[i] < v2[j]) return -1;
10         while (i < m && v1[i++]) return 1;
11         while (j < n && v2[j++]) return -1;
12         return 0;
13     }
14 private:
15     vector<int> version(string& version) {
16         version += "."; 
17         stringstream vs(version);
18         vector<int> v;
19         string t;
20         while (getline(vs, t, '.'))
21             v.push_back(stoi(t));
22         return v;
23     }
24 };

 

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4740846.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值