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题意:比较版本号的大小。
思路:字符串的处理,stringstream的运用以及string成员函数find(), substr()的运用
class Solution {
public:
int compareVersion(string version1, string version2) {
if (version1.find('.') == -1 && version2.find('.') == -1){
return compare(version1, version2);
}
else{
if (version1.find('.') == -1 && version2.find('.') != -1){
int p = version2.find('.');
string s = version2.substr(0, p);
version2 = version2.substr(p + 1, version2.size());
int r = compare(version1, s);
if (r == 0){
return compareVersion("0", version2);
}
else{
return r;
}
}else if (version1.find('.') != -1 && version2.find('.') == -1){
int p = version1.find('.');
string s = version1.substr(0, p);
version1 = version1.substr(p + 1, version1.size());
int r= compare(s, version2);
if (r == 0){
return compareVersion(version1, "0");
}
else{
return r;
}
}
else{
int p = version1.find('.');
string s1 = version1.substr(0, p);
version1 = version1.substr(p + 1, version1.size());
int q = version2.find('.');
string s2 = version2.substr(0, q);
version2 = version2.substr(q + 1, version2.size());
int r = compare(s1, s2);
if (r == 0){
return compareVersion(version1, version2);
}else{
return r;
}
}
}
}
int compare(string s1, string s2){
stringstream s;
int a, b;
s << s1;
s >> a;
s.clear();
s << s2;
s >> b;
if (a > b)
return 1;
else if (a < b)
return -1;
else
return 0;
}
};