Leetcode: Compare Version Numbers
原创
©著作权归作者所有:来自51CTO博客作者TheOneGIS的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目:
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.
Here is an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37
思路分析:
先将version字符串以点号分割放入vector中,然后将vector中的每个字符string类型转成int类型,然后依次进行int的比较。
C++示例代码:
class Solution
{
private:
/*
将str以ch进行分割,结果保存在vector中返回
*/
vector<string> split(string str, char ch)
{
vector<string> result;
int index = 0;
int count = 0;
string substr;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == ch)
{
count = i - index;
substr = str.substr(index, count);
index = i + 1;
result.push_back(substr);
}
}
count = str.length()- index;
substr = str.substr(index, count);
result.push_back(substr);
return result;
}
/*
将vector中的string类型转换成int类型
这里使用到了库函数stoi()
*/
vector<int> toInt(vector<string> numbers)
{
int size = numbers.size();
vector<int> intnums;
intnums.reserve(size);
for (int i = 0; i < size; i++)
{
intnums.push_back(stoi(numbers[i]));
}
return intnums;
}
public:
int compareVersion(string version1, string version2)
{
vector<string> strversion1 = split(version1, '.');
vector<int> intversion1 = toInt(strversion1);
vector<string> strversion2 = split(version2, '.');
vector<int> intversion2 = toInt(strversion2);
int size1 = intversion1.size();
int size2 = intversion2.size();
int size = size1;
/*
下面的ifelse是将两个vector的个数补齐,即使vector的 size是一样的,不足的补零。
*/
if (size1 > size2)
{
size = size1;
for (int i = size2; i < size; i++)
{
intversion2.push_back(0);
}
}
else if (size1 < size2)
{
size = size2;
for (int i = size1; i < size; i++)
{
intversion1.push_back(0);
}
}
for (int i = 0; i < size; i++)
{
if (intversion1[i] > intversion2[i])
{
return 1;
}
else if (intversion1[i] < intversion2[i])
{
return -1;
}
}
return 0;
}
};