【LeetCode】165. Compare Version Numbers
问题描述
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
分析
看上去是只要使用split
切割成数组就行了,但实际上还是有几个坑的,比如说01
与1
是同一个版本,1.0
与1
是同一个版本.
代码
class Solution {
public:
int compareVersion(string version1, string version2) {
vector<string> v1 = split(version1,".");
vector<string> v2 = split(version2, ".");
int len = max(v1.size(), v2.size());
for(int i=0,j=0;i<len;i++,j++) {
int a = 0;
if(i<v1.size()) {
a = atoi(v1[i].c_str());
}
int b = 0;
if(j<v2.size()){
b = atoi(v2[j].c_str());
}
if(a > b) {
return 1;
} else if(a < b) {
return -1;
}
}
return 0;
}
std::vector<std::string> split(const std::string& s, const std::string& delim)
{
std::vector<std::string> elems;
size_t pos = 0;
size_t len = s.length();
size_t delim_len = delim.length();
if (delim_len == 0) return elems;
while (pos < len)
{
int find_pos = s.find(delim, pos);
if (find_pos < 0)
{
elems.push_back(s.substr(pos, len - pos));
break;
}
elems.push_back(s.substr(pos, find_pos - pos));
pos = find_pos + delim_len;
}
return elems;
}
};