日期:2026年10月24日
LeetCode 題目連結:2409. Count Days Spent Together
解題想法
簡單題。題目給 4 個長度皆為 5 的字串,格式為 MM-DD,MM 代表月,DD 代表日。4 個字串分別是代表 Alice 抵達的日期 arriveAlice,Alice 離開的日期 leaveAlice,Bob 抵達的日期 arriveBob,Bob 離開的日期 leaveBob。計算 Alice 與 Bob 一起待在羅馬的天數。假設是平年,2 月只有 28 天。
由於日期格式很困定,可以用 Python 的字串切片或是 C++ 的 substr,將字串中的月、日分開,轉成整數。如果用 C 語言比較麻煩,我是用索引值取出字元再減去 '0' 換成對應的整數,每個位數都要分開算。在計算天數時,我將日期全部轉成由1月1日開始的累計天數。為了計算月份對應的天數,我開一個長度為 13 的陣列 $month = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365)$,記錄經過完整的月份時共經過幾天。答案為兩個人離開日期最小值 - 兩個人離開日期最大值,如果答案是負的則回傳 0。
Python 程式碼
Runtime: 0 ms, beats 100.00%. Memory: 19.29 MB, beats 79.30%.
class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
month = (0, 31, 59, 90, 120, 151, 181,
212, 243, 273, 304, 334, 365)
arriveAliceDays = month[int(arriveAlice[:2]) - 1] + int(arriveAlice[3:])
leaveAliceDays = month[int(leaveAlice[:2]) - 1] + int(leaveAlice[3:])
arriveBobDays = month[int(arriveBob[:2]) - 1] + int(arriveBob[3:])
leaveBobDays = month[int(leaveBob[:2]) - 1] + int(leaveBob[3:])
ans = min(leaveAliceDays, leaveBobDays) - max(arriveAliceDays, arriveBobDays) + 1
return ans if ans > 0 else 0
C++ 程式碼
Runtime: 0 ms, beats 100.00%. Memory: 8.05 MB, beats 38.18%.
class Solution {
public:
int countDaysTogether(string arriveAlice, string leaveAlice, string arriveBob, string leaveBob) {
int month[13] =
{0, 31, 59, 90, 120, 151, 181,
212, 243, 273, 304, 334, 365};
int arriveAliceDays = month[stoi(arriveAlice.substr(0, 2)) - 1] + stoi(arriveAlice.substr(3));
int leaveAliceDays = month[stoi(leaveAlice.substr(0, 2)) - 1] + stoi(leaveAlice.substr(3));
int arriveBobDays = month[stoi(arriveBob.substr(0, 2)) - 1] + stoi(arriveBob.substr(3));
int leaveBobDays = month[stoi(leaveBob.substr(0, 2)) - 1] + stoi(leaveBob.substr(3));
int ans = min(leaveAliceDays, leaveBobDays) - max(arriveAliceDays, arriveBobDays) + 1;
return (ans > 0 ? ans : 0);
}
};
C 語言程式碼
Runtime: 0 ms, beats 100.00%. Memory: 8.48 MB, beats 62.50%.
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
int countDaysTogether(char* arriveAlice, char* leaveAlice, char* arriveBob, char* leaveBob) {
int month[13] =
{0, 31, 59, 90, 120, 151, 181,
212, 243, 273, 304, 334, 365};
int arriveAliceDays = month[(arriveAlice[0] - '0') * 10 + (arriveAlice[1] - '0') - 1] + (arriveAlice[3] - '0') * 10 + (arriveAlice[4] - '0');
int leaveAliceDays = month[(leaveAlice[0] - '0') * 10 + (leaveAlice[1] - '0') - 1] + (leaveAlice[3] - '0') * 10 + (leaveAlice[4] - '0');
int arriveBobDays = month[(arriveBob[0] - '0') * 10 + (arriveBob[1] - '0') - 1] + (arriveBob[3] - '0') * 10 + (arriveBob[4] - '0');
int leaveBobDays = month[(leaveBob[0] - '0') * 10 + (leaveBob[1] - '0') - 1] + (leaveBob[3] - '0') * 10 + (leaveBob[4] - '0');
int ans = min(leaveAliceDays, leaveBobDays) - max(arriveAliceDays, arriveBobDays) + 1;
return (ans > 0 ? ans : 0);
}
沒有留言:
張貼留言