题目
给你两个版本号 version1 和 version2,请你比较它们。
版本号由一个或多个修订号组成,各修订号由一个 . 连接。每个修订号由多位数字组成,可能包含前导零。每个版本号至少包含一个字符。修订号从左到右编号,下标从 0 开始,最左边的修订号下标为 0,下一个修订号下标为 1,以此类推。例如,2.5.33 和 0.1 都是有效的版本号。
比较版本号时,请按从左到右的顺序依次比较它们的修订号。比较修订号时,只需比较忽略任何前导零后的整数值。也就是说,修订号 1 和修订号 001 相等。如果版本号没有指定某个下标处的修订号,则该修订号视为 0。例如,版本 1.0 小于版本 1.1,因为它们下标为 0 的修订号相同,而下标为 1 的修订号分别为 0 和 1,0 < 1。
返回规则如下:
- 如果
version1 > version2 返回 1, - 如果
version1 < version2 返回 -1, - 除此之外返回
0。
demo
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
// Helper function to split the version string into revision numbers
std::vector<int> splitVersion(const std::string& version) {
std::vector<int> revisions;
std::stringstream ss(version);
std::string revision;
while (std::getline(ss, revision, '.')) {
// Remove leading zeros
auto it = std::find_if(revision.rbegin(), revision.rend(), [](char c) { return c != '0'; });
std::string number_str = (it == revision.rend()) ? "0" : std::string(revision.begin(), it.base());
// Convert the remaining part (or "0" if all were zeros) to an integer
revisions.push_back(std::stoi(number_str));
}
// If the versions have different number of revisions, pad with zeros
while (revisions.size() < 4) { // Assuming a maximum of 4 revisions for simplicity, adjust as needed
revisions.push_back(0);
}
// Trim trailing zeros (optional, depending on how you want to handle versions like "1.000")
// This step is not strictly necessary for comparison as padding with zeros should make them equivalent
// but can be useful for display purposes
while (!revisions.empty() && revisions.back() == 0) {
revisions.pop_back();
}
return revisions;
}
int solution(std::string version1, std::string version2) {
std::vector<int> v1 = splitVersion(version1);
std::vector<int> v2 = splitVersion(version2);
// Ensure both versions have the same number of revisions by padding with zeros (already done in splitVersion)
size_t max_length = std::max(v1.size(), v2.size());
v1.resize(max_length, 0);
v2.resize(max_length, 0);
// Compare the versions
for (size_t i = 0; i < max_length; ++i) {
if (v1[i] > v2[i]) {
return 1;
} else if (v1[i] < v2[i]) {
return -1;
}
}
return 0;
}
int main() {
std::cout << (solution("0.1", "1.1") == -1) << std::endl; // Should print 1 (true)
std::cout << (solution("1.0.1", "1") == 1) << std::endl; // Should print 1 (true), but note that "1" is equivalent to "1.0.0"
std::cout << (solution("7.5.2.4", "7.5.3") == -1) << std::endl; // Should print 1 (true)
std::cout << (solution("1.0", "1.0.0") == 0) << std::endl; // Should print 1 (true) because they are equal after padding
return 0;
}