2409. Count Days Spent Together
约 1 分钟
LeetCode 每日一题:Count Days Spent Together
本页目录
Alice and Bob are traveling to Rome for separate business meetings.
You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city from the dates arriveBob to leaveBob (inclusive). Each will be a 5-character string in the format "MM-DD", corresponding to the month and day of the date.
Return the total number of days that Alice and Bob are in Rome together.
You can assume that all dates occur in the same calendar year, which is not a leap year. Note that the number of days per month can be represented as: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].
Constraints:
- All dates are provided in the format
"MM-DD". - Alice and Bob's arrival dates are earlier than or equal to their leaving dates.
- The given dates are valid dates of a non-leap year.
思路:看图写话
本题分两步走:
- 把MM-DD类型的时间转化为天数
- 求两个时间区间的交集
代码
python
class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def to_day(date: str):
month, day = int(date[:2]), int(date[-2:])
return sum(months[:month-1]) + day
a_start, a_end, b_start, b_end = to_day(arriveAlice),to_day(leaveAlice), to_day(arriveBob),to_day(leaveBob)
return max(0, min(a_end, b_end) - max(a_start, b_start)+1)系列每日一题 →
标签看图写话