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 ver1;
vector 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;
}
}
};
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(id1lev2){
return 1;
}else if(lev1