> 文章列表 > leetcode 统计共同度过的日子数( 2409.)

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

leetcode 统计共同度过的日子数( 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] 。

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

题解思路

  1. 首先把到达与离开日期都变成天数
  2. 求交集,交集是最小的离开日期减去最大的到达日期,并+1。

代码

class Solution {
public:int countDaysTogether(string arriveAlice, string leaveAlice, string arriveBob, string leaveBob) {vector<int> month_day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};vector<int> prefix_day(1,0);for(auto day : month_day){prefix_day.emplace_back(prefix_day.back() + day);}int arriveAliceDay = manyDay(arriveAlice, prefix_day);int leaveAliceDay = manyDay(leaveAlice, prefix_day);int arriveBobDay = manyDay(arriveBob, prefix_day);int leaveBobDay = manyDay(leaveBob, prefix_day);return max(0, min(leaveAliceDay, leaveBobDay) - max(arriveAliceDay, arriveBobDay) + 1);}int manyDay(string month_day,vector<int> prefix_day){int month = stoi(month_day.substr(0,2));int day = stoi(month_day.substr(3,5));return day+prefix_day[month-1];}
};

知识点

  • 知识点1. stoi() 将string 转成int类型
  • 知识点2. string.substr(int start,int end) start包含,end不包含