medium程度题
题目:
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
AC解
class Solution
{
public:
int compareVersion(string version1, string version2)
{
int i = 0;
long long sum1 = 0,sum2 = 0;
vector<long long> s1,s2;
while(version1[i] != '\0')
{ //提取元素
if(version1[i] == '.')
{
s1.push_back(sum1);
sum1 = 0;
}
else
{
sum1 = 10 * sum1 + (version1[i] - '0');
}
i++;
}
s1.push_back(sum1);//添加最后一个到容器
i = 0;
while(version2[i] != '\0')
{
if(version2[i] == '.')
{
s2.push_back(sum2);
sum2 = 0;
}
else
{
sum2 = 10 * sum2 + (version2[i] - '0');
}
i++;
}
s2.push_back(sum2);//添加最后一个到容器
if(s1.size() < s2.size())
{
s1.insert(s1.end(),s2.size() - s1.size(),0);
}
if(s1.size() > s2.size())
{
s2.insert(s2.end(),s1.size() - s2.size(),0);
}
if(s1 == s2) return 0;
if(s1 > s2) return 1;
if(s1 < s2) return -1;
/*i = s1.size() < s2.size() ? s1.size():s2.size();
for(int j = 0 ; j < i; j++)
{
if(s1[j] < s2[j])
return -1;
else if(s1[j] > s2[j])
return 1;
}
if(s1.size() > s2.size())
{
for(int j = 0 ; j < fabs(s1.size() - s2.size()) ; j++)
{
if(s1[i] > '0')
return 1;
}
}
else
{
for(int j = 0 ; j < fabs(s1.size() - s2.size()) ; j++)
{
if(s2[i] > '0')
return -1;
}
}
return 0;*/
}
};
我的想法是把所有由.分隔的整数提取出来放入一个容器
最开始使用了注释里的解,超时! 最后查文档知道容器Vector重载了一系列比较操作符,依据字典顺序比较大小引用自http://en.cppreference.com/w/cpp/container/vector/operator_cmp
lhs and
rhs are equal, that is, whether
lhs.size() == rhs.size() and each element in
lhs compares equal with the element in
rhs at the same position.
lhs and
rhs lexicographically. The comparison is performed by a function equivalent to
std::lexicographical_compare.
为了满足题意的比较,我将容器最终大小统一,即在小的容器后面插入0使其最终与大的容器大小相同。

本文介绍了一种有效的版本号比较算法,通过将版本号拆分成序列并进行逐位对比,实现了快速判断两个版本号之间的大小关系。

被折叠的 条评论
为什么被折叠?



