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:
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
注意一下特殊情况:
001 与 1;
10.3.4.0与10.3.4;
思路是每次遇见一个小数点,就将此前数字转换为数值并通过向量存储,然后从向量开始端比较大小即可:
class Solution {
public:
int atoi1(char *s,int start,int end){
int sum=0;
for(int i=start;i<end;i++)
{sum*=10;
sum+=s[i]-'0';}
return sum;}//字符串转数值
vector<int>getint(char *s){
int l=strlen(s);
int start=0;
vector<int>res;
for(int i=0;i<=l;i++){
if(s[i]=='.'||s[i]=='\0'){res.push_back(atoi1(s,start,i));start=i+1;}
}
return res;
}//版本号字符串形式转换为由数字小数点为间隔的若干个数值,并利用向量存储
int compareVersion(string version1, string version2) {
int l1=version1.length();
char *version11=new char [l1+10];
for(int i=0;i<l1;i++)
version11[i]=version1[i];
version11[l1]='\0';
int l2=version2.length();
char *version22=new char [l2+1];
for(int i=0;i<l2;i++)
version22[i]=version2[i];
version22[l2]='\0';//将string对象转换为char*
vector<int> v1=getint(version11);
vector<int> v2=getint(version22);
int i=0;
cout<<v1.size()<<" "<<v2.size()<<endl;
while(i!=v1.size()&&i!=v2.size()){
int x=v1.at(i);
int y=v2.at(i);
if(x<y)return -1;
else if(x>y)return 1;
else {i++;continue;}
}//逐一比较
if(i!=v1.size()&&v1.at(i)!=0)return 1;
if(i!=v2.size()&&v2.at(i)!=0)return -1;
return 0;}
};