LeetCode:Compare Version Numbers
2015-10-12 08:30
405 查看
这道题的难度是Easy,但是通过率不高,主要是题目给的不是很明确,测试的场景也比较复杂。
经过多番调试,终于Accepted。目前的解决方式采用了递归。采用非递归的方式,需要记录连续两个'.'的位置,觉得操作太烦了,故没有使用。
int compareVersion(string version1, string version2)
{
int
pos1 = version1.find_first_of('.');
int
pos2 = version2.find_first_of('.');
int
m,n;
if
(pos1!=-1)
{
m
= atoi(version1.substr(0,pos1).c_str());
}
else
{
m=atoi(version1.c_str());
}
if
(pos2!=-1)
{
n
= atoi(version2.substr(0,pos2).c_str());
}
else
{
n
= atoi(version2.c_str());
}
if
(m==n)
{
if
(pos1!=-1&&pos2!=-1)
{
return
compareVersion(version1.substr(pos1+1),version2.substr(pos2+1));
}
else
if(pos1!=-1)
{
return
compareVersion(version1.substr(pos1+1),"0");
}
else
if (pos2!=-1)
{
return
compareVersion("0",version2.substr(pos2+1));
}
else
{
return
0;
}
}
return
m<<span
style="color:navy">n?-1:1;
}
经过多番调试,终于Accepted。目前的解决方式采用了递归。采用非递归的方式,需要记录连续两个'.'的位置,觉得操作太烦了,故没有使用。
int compareVersion(string version1, string version2)
{
int
pos1 = version1.find_first_of('.');
int
pos2 = version2.find_first_of('.');
int
m,n;
if
(pos1!=-1)
{
m
= atoi(version1.substr(0,pos1).c_str());
}
else
{
m=atoi(version1.c_str());
}
if
(pos2!=-1)
{
n
= atoi(version2.substr(0,pos2).c_str());
}
else
{
n
= atoi(version2.c_str());
}
if
(m==n)
{
if
(pos1!=-1&&pos2!=-1)
{
return
compareVersion(version1.substr(pos1+1),version2.substr(pos2+1));
}
else
if(pos1!=-1)
{
return
compareVersion(version1.substr(pos1+1),"0");
}
else
if (pos2!=-1)
{
return
compareVersion("0",version2.substr(pos2+1));
}
else
{
return
0;
}
}
return
m<<span
style="color:navy">n?-1:1;
}
相关文章推荐
- Windows&nbsp;Atom&nbsp;使用
- 过去的2014
- 命名规则
- python&nbsp;记录
- 日志级别
- 公共DNS
- Perforce使用指南_forP4V
- 转载:notepad++常用设置
- printf&nbsp;输出补0
- Largest&nbsp;prime&nbsp;factor
- 记个公式
- c++&nbsp;关于char&nbsp;*的…
- 时间转化
- Cmder&nbsp;中文乱码设置
- Cmder&nbsp;alais&nbsp;设置
- Python&nbsp;gzip
- Zlib&nbsp;gzip&nbsp;解压缩
- gooreplacer&nbsp;解决国外网站加…
- 九九乘法表
- Java中的ReentrantLock和synchronized两种锁定机制的对比