LeetCode Compare Version Numbers
原创
©著作权归作者所有:来自51CTO博客作者fox64194167的原创作品,请联系作者获取转载授权,否则将追究法律责任
1.题目
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:
2.解答
class Solution {
public:
vector<string> getAllVersionString(string version1){
vector<string> allVersion1;
string oneVersion1;
for(int i = 0; i < version1.size(); ++i){
if(version1[i] != '.'){
oneVersion1.push_back(version1[i]);
}else{
allVersion1.push_back(oneVersion1);
oneVersion1.clear();
}
}
allVersion1.push_back(oneVersion1);
return allVersion1;
}
int compareVer(vector<string> allVersion1, vector<string> allVersion2){
for(int i = 0; i < allVersion1.size(); ++i){
if(i < allVersion2.size()){
if(atoi(allVersion1[i].c_str()) < atoi(allVersion2[i].c_str())){
return -1;
}else if(atoi(allVersion1[i].c_str()) > atoi(allVersion2[i].c_str())){
return 1;
}
}else{
if(atoi(allVersion1[i].c_str()) > 0){
return 1;
}
}
}
return 0;
}
int compareVersion(string version1, string version2) {
vector<string> allVersion1 = getAllVersionString(version1);
vector<string> allVersion2 = getAllVersionString(version2);
int result = 0;
if(allVersion1.size() >= allVersion2.size()){
result = compareVer(allVersion1, allVersion2);
}else if(allVersion2.size() > allVersion1.size()){
result = -compareVer(allVersion2, allVersion1);
}
return result;
}
};
C++中好像没有分割的函数的,感觉我也写麻烦了。