问题
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.
例子
0.1 < 1.1 < 1.2 < 13.37
分析
题目没有说明.出现的次数,实际上10.7.3.0.1这种版本号也是合法的。3.0.0这种以0为结尾的版本号同样是合法的。
自己实现一个split方法,将版本号根据.号切割成若干版本数字,然后从左到右依次比较大小。要注意3.0和3.0.0这种情况,两者是相等的版本号。
要点
- 切割字符串
- 比较大小(类比sort算法的comparator函数)
时间复杂度
O(n)
空间复杂度
O(n)
代码
class Solution {
public:
int compareVersion(string version1, string version2) {
vector<int> versions1, versions2;
split(version1, ".", versions1);
split(version2, ".", versions2);
int i = 0;
for (; i < versions1.size() && i < versions2.size(); i++) {
if (versions1[i] > versions2[i]) return 1;
if (versions1[i] < versions2[i]) return -1;
}
for (; i < versions1.size(); i++)
if (versions1[i] != 0) return 1;
for (; i < versions2.size(); i++)
if (versions2[i] != 0) return -1;
return 0;
}
private:
void split(const std::string &s, std::string delim, std::vector<int> &res) {
size_t last = 0;
size_t index = s.find_first_of(delim, last);
while (index != std::string::npos) {
if (index > last) res.push_back(stoi(s.substr(last, index - last)));
last = index + 1;
index = s.find_first_of(delim, last);
}
if (index > last)
res.push_back(stoi(s.substr(last, index - last)));
}
};
直接遍历字符
class Solution {
public:
int compareVersion(string version1, string version2) {
int n1 = version1.size(), n2 = version2.size();
int num1 = 0, num2 = 0;
for (int i = 0, j = 0; i < n1 || j < n2; i++, j++) {
while (i < n1 && version1[i] != '.')
num1 = num1 * 10 + version1[i++] - '0';
while (j < n2 && version2[j] != '.')
num2 = num2 * 10 + version2[j++] - '0';
if (num1 > num2) return 1;
if (num1 < num2) return -1;
num1 = num2 = 0;
}
return 0;
}
};