> 文章列表 > 入门力扣自学笔记259 C++ (题目编号:2409)

入门力扣自学笔记259 C++ (题目编号:2409)

入门力扣自学笔记259 C++ (题目编号:2409)

2409. 统计共同度过的日子数

题目:

Alice 和 Bob 计划分别去罗马开会。

给你四个字符串 arriveAlice ,leaveAlice ,arriveBob 和 leaveBob 。Alice 会在日期 arriveAlice 到 leaveAlice 之间在城市里(日期为闭区间),而 Bob 在日期 arriveBob 到 leaveBob 之间在城市里(日期为闭区间)。每个字符串都包含 5 个字符,格式为 "MM-DD" ,对应着一个日期的月和日。

请你返回 Alice和 Bob 同时在罗马的天数

你可以假设所有日期都在 同一个 自然年,而且 不是 闰年。每个月份的天数分别为:[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 。


示例 1:

输入:arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19"
输出:3
解释:Alice 从 8 月 15 号到 8 月 18 号在罗马。Bob 从 8 月 16 号到 8 月 19 号在罗马,他们同时在罗马的日期为 8 月 16、17 和 18 号。所以答案为 3 。


示例 2:

输入:arriveAlice = "10-01", leaveAlice = "10-31", arriveBob = "11-01", leaveBob = "12-31"
输出:0
解释:Alice 和 Bob 没有同时在罗马的日子,所以我们返回 0 。


提示:

所有日期的格式均为 "MM-DD" 。
Alice 和 Bob 的到达日期都 早于或等于 他们的离开日期。
题目测试用例所给出的日期均为 非闰年 的有效日期。


来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-days-spent-together
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


思路:

这道题总共有两种情况,分别为:

1.Alice和Bob的日期不存在交集
也就是leaveBobDate < arriveAliceDate || leaveAliceDate < arriveBobDate的情况,直接返回0即可
2.Alice和Bob的日期存在交集
他们共同在城里的天数就是:min(leaveAliceDate, leaveBobDate) - max(arriveAliceDate, arriveBobDate)


代码:

class Solution {
private:struct Date{int month;int day;bool operator< (const Date& another){if(this->month == another.month)return this->day < another.day;return this->month < another.month;}};static Date getDate(const string& date){int index = 0;while(date[index] != '-')index += 1;int month = stoi(date.substr(0,index));int day = stoi(date.substr(index + 1,date.size() - index - 1));return (struct Date){.month = month,.day = day};}const vector<int> daysEachMonth{31,28,31,30,31,30,31,31,30,31,30,31};int countDays(const Date& from,const Date& to){if(from.month == to.month)return to.day - from.day + 1;int days = daysEachMonth[from.month - 1] - from.day + 1;for(int month = from.month + 1;month < to.month;month++)days += daysEachMonth[month - 1];return days + to.day;}public:int countDaysTogether(string arriveAlice, string leaveAlice, string arriveBob, string leaveBob) {Date arriveAliceDate = getDate(arriveAlice);Date leaveAliceDate = getDate(leaveAlice);Date arriveBobDate = getDate(arriveBob);Date leaveBobDate = getDate(leaveBob);if(leaveBobDate < arriveAliceDate || leaveAliceDate < arriveBobDate)return 0;Date start = arriveAliceDate;if(arriveAliceDate < arriveBobDate)start = arriveBobDate;Date end = leaveAliceDate;if(leaveBobDate < leaveAliceDate)end = leaveBobDate;return countDays(start,end);}
};