'''
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.
You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0.
'''
class Solution1(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
s1 = version1.split('.')
s2 = version2.split('.')
n = min(len(s1), len(s2))
for i in range(n):
if int(s1[i]) > int(s2[i]):
return 1
elif int(s1[i]) < int(s2[i]):
return -1
if len(s1) > len(s2) and int(''.join(s1[n:])) > 0:
return 1
elif len(s1) < len(s2) and int(''.join(s2[n:])) > 0:
return -1
else:
return 0
#without built-in functions (specially split() and join())
class Solution(object):
def sp(self, string, splitter=' '):
#split string into a list splitted by the splitter
temp = ''
sl = []
for i in string:
if i != splitter:
temp += i
else:
if temp:
sl.append(temp)
temp = ''
if temp:
sl.append(temp)
temp = ''
return sl
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
s1 = self.sp(version1, '.')
s2 = self.sp(version2, '.')
n = min(len(s1), len(s2))
for i in range(n):
if int(s1[i]) > int(s2[i]):
return 1
elif int(s1[i]) < int(s2[i]):
return -1
s3sum = 0
if n == len(s1):
for i in s2[n:]:
s3sum += int(i)
if s3sum > 0: break
else:
for i in s1[n:]:
s3sum += int(i)
if s3sum > 0: break
if len(s1) > len(s2) and s3sum > 0:
return 1
elif len(s1) < len(s2) and s3sum > 0:
return -1
else:
return 0
No comments:
Post a Comment