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
version number,顾名思义就是版本号
的意思啦。它题目中给的例子不太直观,我自己举一个例子就是:
1.2 < 1,10
因为1.10和1.1是不一样的,1.10代表the tenth revision
,而1.1代表the first revision
。所以这道题要将version string按照“.”分段,然后逐段比较。
有一点需要注意的是,一开始我的代码wrong answer,看到它卡在测试案例
“1.1”,”1.01.0”
对两个version string预处理后,得到的两组数据分别为:1,1和1,1,0。其实这种情况是相等的,但是一开始的代码中,数组没有初始化,array1[2]为负数,小于0,所以返回-1。修改最后的AC代码为:
class Solution {
public:
vector<string> split(string s1,char c){
vector<string> ans;
string::size_type pos1, pos2;
pos2= s1.find(c);
pos1 = 0;
while (string::npos != pos2){
ans.push_back(s1.substr(pos1,pos2-pos1));
pos1 = pos2 + 1;
pos2 = s1.find(c, pos1);
}
if (pos1 != s1.length()){
ans.push_back(s1.substr(pos1));
}
return ans;
}
int compareVersion(string version1, string version2) {
vector<string> s1 = split(version1, ‘.‘);
vector<string> s2 = split(version2, ‘.‘);
int maxLen = s1.size()>s2.size() ? s1.size() : s2.size();
int* array1 = new int[maxLen];
int* array2 = new int[maxLen];
memset(array1, 0, maxLen*sizeof(int));
memset(array2, 0, maxLen*sizeof(int));
int i = 0;
for (i = 0; i < s1.size(); i++){
array1[i] = atoi(s1[i].c_str());
}
for (i = 0; i < s2.size(); i++){
array2[i] = atoi(s2[i].c_str());
}
for (i = 0; i < maxLen; i++){
if (array1[i]>array2[i])
return 1;
else if (array1[i] < array2[i])
return -1;
}
return 0;
}
};
[LeetCode]Compare Version Numbers
原文:http://blog.csdn.net/kaitankedemao/article/details/43611971