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
class Solution {
public:
int compareVersion(string version1, string version2)
{
int len1 = version1.length();
int len2 = version2.length();
vector<int> num1, num2;
char *s1 = (char *)version1.c_str();
char *s2 = (char *)version2.c_str();
//分割
char *d = ".";
char *p = strtok(s1, d);
while(p)
{
int n = atoi(p);
num1.push_back(n);
p = strtok(NULL, d);
}
p = strtok(s2, d);
while(p)
{
int n = atoi(p);
num2.push_back(n);
p = strtok(NULL, d);
}
//比较
int n1 = num1.size();
int n2 = num2.size();
int i = 0, j = 0;
while(i<n1 && j<n2)
{
if(num1[i] < num2[j])
return -1;
else if(num1[i] > num2[j])
return 1;
else
{
i++;
j++;
}
}
//如果version1比较长
if(i < n1)
{
while(i < n1)
{
if(num1[i] != 0)
{
return 1;
}
i++;
}
return 0;
}
//如果version2比较长
else if(j < n2)
{
while(j < n2)
{
if(num2[j] != 0)
{
return -1;
}
j++;
}
return 0;
}
return 0;
}
};