首页 > 代码库 > LeetCode—Compare Version Numbers
LeetCode—Compare Version Numbers
Compare two version numbers version1 and version1.
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
刚拿到题目的时候主要是对题目理解了很久啊
其实意思很简单,每一个字符串中有一些数字和‘.’,‘.’的作用只是为了把数字分开,然后依次比较大小
在自己写的很土的方法中,就是简单的先把两个string分解到对应的vector当中,这里有几个需要注意的地方
两个字符串中的数字长度不是相等的,所以如果前面都相等还要看后面
11.22.33.00.00000 = 11.22.33
11.22.33.01 > 11.22.33
还有就是字符串最后面是没有‘.‘符号的,这里需要注意
class Solution { public: int compareVersion(string version1, string version2) { vector<int> ver1; vector<int> ver2; int val1 = 0,val2 = 0; int i = 0,j = 0; while (i < version1.length()) { if(version1[i] != '.') { val1 = val1*10+(version1[i]-'0'); } else { ver1.push_back(val1); val1 = 0; } i++; } while (j < version2.length()) { if (version2[j] != '.') { val2 = val2*10+(version2[j]-'0'); } else { ver2.push_back(val2); val2 = 0; } j++; } ver1.push_back(val1); ver2.push_back(val2); bool flag = ver1.size() <= ver2.size(); int length = flag? ver1.size():ver2.size(); for (i = 0; i < length; i++) { if (ver1[i] > ver2[i]) { return 1; } else if(ver1[i] < ver2[i]) { return -1; } } if (flag) { for (i = length; i < ver2.size(); i++) { if (ver2[i] != 0) { return -1; } } return 0; } else { for (i = length; i < ver1.size(); i++) { if (ver1[i] != 0) { return 1; } } return 0; } } };
下面是网上的一些别的算法,思想上都大同小异,但是代码因为在while循环内,而且只循环一遍着实是简便了很多:
class Solution { public: int compareVersion(string version1, string version2) { int lev1=0,lev2=0; int id1=0,id2=0; while(id1!=version1.length()||id2!=version2.length()){ lev1=0; while(id1<version1.length()){ if(version1[id1]=='.'){ ++id1; break; } lev1=lev1*10+(version1[id1]-'0'); ++id1; } lev2=0; while(id2<version2.length()){ if(version2[id2]=='.'){ ++id2; break; } lev2=lev2*10+(version2[id2]-'0'); ++id2; } if(lev1>lev2){ return 1; }else if(lev1<lev2){ return -1; } } return 0;//equal } };
LeetCode—Compare Version Numbers