可能字符串中没有‘.',或者有多个‘.',所以用递归的方法更加好
class Solution {
public:
int compareVersion(string version1, string version2) {
if(version1 == version2)
return 0;
int pos1 = version1.find_first_of('.');
int pos2 = version2.find_first_of('.');
pos1 = pos1 == string::npos?version1.size():pos1;
pos2 = pos2 == string::npos?version2.size():pos2;
int l1 = atoi(version1.substr(0,pos1).c_str());
int l2 = atoi(version2.substr(0,pos2).c_str());
pos1 = pos1 == version1.size()?pos1:++pos1;
pos2 = pos2 == version2.size()?pos2:++pos2;
if(l1 != l2)
return l1 > l2?1:-1;
return compareVersion(version1.substr(pos1),version2.substr(pos2));
}
};
本文介绍了一种使用递归方法来比较两个软件版本号大小的算法实现。通过查找每个版本号中的点分隔符来逐段比较数字部分,最终确定两个版本的大小关系。
1049

被折叠的 条评论
为什么被折叠?



