LeetCode刷题实战165:比较版本号
共 3661字,需浏览 8分钟
·
2021-01-26 14:49
Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.
To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.
Return the following:
If version1 < version2, return -1.
If version1 > version2, return 1.
Otherwise, return 0.
题意
如果 version1 > version2 返回 1,
如果 version1 < version2 返回 -1,
除此之外返回 0。
示例 1:
输入:version1 = "1.01", version2 = "1.001"
输出:0
解释:忽略前导零,"01" 和 "001" 都表示相同的整数 "1"
示例 2:
输入:version1 = "1.0", version2 = "1.0.0"
输出:0
解释:version1 没有指定下标为 2 的修订号,即视为 "0"
示例 3:
输入:version1 = "0.1", version2 = "1.1"
输出:-1
解释:version1 中下标为 0 的修订号是 "0",version2 中下标为 0 的修订号是 "1" 。0 < 1,所以 version1 < version2
示例 4:
输入:version1 = "1.0.1", version2 = "1"
输出:1
示例 5:
输入:version1 = "7.5.2.4", version2 = "7.5.3"
输出:-1
解题
思路:
class Solution {
public:
int compareVersion(string version1, string version2) {
int versionOneSize = version1.size();
int versionTwoSize = version2.size();
int maxSize = max(versionOneSize, versionTwoSize);//获取长度的最大值
vector<int> numsVersionOne(maxSize, 0);//用于存放version1各级修订号的字符子串转化为int
vector<int> numsVersionTwo(maxSize, 0);//用于存放version2各级修订号的字符子串转化为int
int tempValue = 0, cnt = 0;
//将version1各级修订号转化为数字
for (int index = 0; index < versionOneSize; ++index) {
tempValue = 0;
while (index < versionOneSize && version1[index] != '.') {
tempValue = tempValue * 10 + version1[index] - '0';
++index;
}
numsVersionOne[cnt++] = tempValue;
}
cnt = 0;
//将version2各级修订号转化为数字
for (int index = 0; index < versionTwoSize; ++index) {
tempValue = 0;
while (index < versionTwoSize && version2[index] != '.') {
tempValue = tempValue * 10 + version2[index] - '0';
++index;
}
numsVersionTwo[cnt++] = tempValue;
}
//将两个版本号的四个数字逐位进行比较
for (int i = 0; i < maxSize; ++i) {
if (numsVersionOne[i] > numsVersionTwo[i]) {
return 1;
}
else if (numsVersionOne[i] < numsVersionTwo[i]) {
return -1;
}
//剩下的就是numsVersionOne[i] == numsVersionTwo[i],需要继续比较下一位
}
return 0;//最后四位都比较完了,还没有分出胜负
}
};