作者Rushia (早瀬ユウカの体操服 )
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Fri May 3 09:20:04 2024
https://leetcode.com/problems/compare-version-numbers/description
165. Compare Version Numbers
給你兩個表示版本的字串,求出哪個版本比較大
If version1 < version2, return -1.
If version1 > version2, return 1.
Otherwise, return 0.
版本以 . 分隔,你可以忽略 0 開頭的版本號 ,也就是0001 和 1 相等。
思路:
1.用函數把版本依據 . 分成好幾組,每組轉成 int 比較大小,如果不相等就返回。
2.如果比完之後還有沒檢查的版本字串,該版本如果遇到大於0一定比較大,否則返回0。
py code:
----------------------------
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
d1 = version1.split('.')
d2 = version2.split('.')
l, r = 0, 0
while l < len(d1) and r < len(d2):
if int(d1[l]) > int(d2[r]):
return 1
elif int(d1[l]) < int(d2[r]):
return -1
l += 1
r += 1
while l < len(d1):
if int(d1[l]) > 0:
return 1
l += 1
while r < len(d2):
if int(d2[r]) > 0:
return -1
r += 1
return 0
----------------------------
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.138.157.129 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1714699207.A.CD8.html
※ 編輯: Rushia (101.138.157.129 臺灣), 05/03/2024 09:21:46
推 SecondRun: 大師 05/03 09:22
推 JIWP: 大師 05/03 09:23
推 wu10200512: 別卷了 嗚嗚哇哇哇 05/03 09:29
推 SecondRun: 今天好簡單 05/03 09:39
→ digua: 大師 05/03 09:54