写在最前面:我承认我菜,对于这道题,我真的无话可说
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:
0.1 < 1.1 < 1.2 < 13.37
比较版本号大小
思路呢,其实也不难,我之前走了很多弯路,还是不理解题意吧,核心思想只有一个,只要不相等,就判断并返回1或者-1
其余一律0
然后就是补0,我一开始想着字符串转int在通过长度次方补成相同长度的字符串,这样就带来一个问题,你补完后根本不知道小数点在哪里,不建议用re.sub去去掉小数点,反而,小数点是你区分字符的重要依据。
用split分离字符,问题又来了,你的for循环循环到长度小的字符串怎么办,重点不在简化判断条件代码,而是你需要怎么进入判断
我的思路是如果循环超过短的字符串,用0去和长的字符串比较。下面上代码
class Solution:
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
newversion1 = version1.split('.')
newversion2 = version2.split('.')
len1 = len(newversion1)
len2 = len(newversion2)
if len1 > len2:
for i in range(len1):
if i<len2:
if int(newversion1[i]) > int(newversion2[i]):
return 1
elif int(newversion1[i]) < int(newversion2[i]):
return -1
elif int(newversion1[i]) > 0:
return 1
return 0
elif len1 < len2:
for i in range(len2):
if i<len1:
if int(newversion1[i]) > int(newversion2[i]):
return 1
elif int(newversion1[i]) < int(newversion2[i]):
return -1
elif int(newversion2[i]) > 0:
return -1
return 0
elif len1 == len2:
for i in range(len1):
if int(newversion1[i]) > int(newversion2[i]):
return 1
elif int(newversion1[i]) < int(newversion2[i]):
return -1
return 0
代码写的稀烂啊,但是能过,核心思想把握住即可,不要慌,问题不大。
依旧放一下java代码吧
class Solution {
public int compareVersion(String version1, String version2) {
String[] version1Array = version1.split("\\.");
String[] version2Array = version2.split("\\.");
int index = 0;
//获取最小长度值
int minLen = Math.min(version1Array.length, version2Array.length);
int diff = 0;
//循环判断每位的大小
while (index < minLen && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) {
index++;
}
if (diff == 0) {
//如果位数不一致,比较多余位数
for (int i = index; i < version1Array.length; i++) {
if (Integer.parseInt(version1Array[i]) > 0) {
return 1;
}
}
for (int i = index; i < version2Array.length; i++) {
if (Integer.parseInt(version2Array[i].trim()) > 0) {
return -1;
}
}
return 0;
} else {
return diff > 0 ? 1 : -1;
}
}
}
java就不细讲了,晚安