- Today
- Total
작심삼일
[LeetCode] 165 | Compare Version Numbers | Python 본문
문제 링크: https://leetcode.com/problems/compare-version-numbers/
문제
Given two version numbers, version1 and version2, compare them.
Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.
To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.
Return the following:
- If version1 < version2, return -1.
- If version1 > version2, return 1.
- Otherwise, return 0.
조건
- 1 <= version1.length, version2.length <= 500
- version1 and version2 only contain digits and '.'.
- version1 and version2 are valid version numbers.
- All the given revisions in version1 and version2 can be stored in a 32-bit integer.
내 풀이
'.'을 기준으로 나눈 후, 각 자리수를 비교한다.
더 짧은 version이 끝났을 때, 긴 version의 자릿수가 0보다 크면 그 version이 더 큰 버전이다.
코드
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
S1, S2 = version1.split('.'), version2.split('.')
for m in range(max(len(S1), len(S2))):
if m < len(S1) and m < len(S2):
if int(S1[m]) < int(S2[m]): return -1
elif int(S1[m]) > int(S2[m]): return 1
elif m < len(S1):
for n in range(m, len(S1)):
if int(S1[n]) != 0: return 1
else:
for n in range(m, len(S2)):
if int(S2[n]) != 0: return -1
return 0
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 413 | Arithmetic Slices | Python (0) | 2022.03.03 |
---|---|
[LeetCode] 392 | Is Subsequence | Python (0) | 2022.03.02 |
[LeetCode] 148 | Sort List | Python (0) | 2022.02.24 |
[LeetCode] 133 | Clone Graph | Python (0) | 2022.02.23 |
[LeetCode] 171 | Excel Sheet Column Number | Python (0) | 2022.02.22 |