LeetCode 2409

给定两个人的到达和离开罗马的日期,求他们在同一城市共同度过的时间。通过比较日期并计算交集来得出答案。示例中,Alice和Bob在8月16日至18日共同在罗马,答案为3天。
摘要由CSDN通过智能技术生成

题目描述:

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 。

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

解题思路

比较他们离开和到达的时间,然后选出时间的交集,判断是否存在交集,最后计算就可。

代码:

class Solution {
public:
    int countDaysTogether(string arriveAlice, string leaveAlice, string arriveBob, string leaveBob) {
 
        //从到达日期中选择一个大的
        string arrive = arriveAlice > arriveBob ? arriveAlice : arriveBob;

        //从离开日期中选择一个小的
        string leave = leaveAlice < leaveBob ? leaveAlice : leaveBob ;

        if(leave < arrive)
            return 0;
        
        int month[13] = {0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        string temp = arrive.substr(0,2);
        int arriveMonth = atoi(temp.c_str());
        temp = arrive.substr(3);
        int arriveDay = atoi(temp.c_str());
        temp = leave.substr(0,2);
        int leaveMonth = atoi(temp.c_str());
        temp = leave.substr(3);
        int leaveDay = atoi(temp.c_str());

        int ans = 0;
        for(int i = arriveMonth ; i < leaveMonth ; i++)
            ans += month[i];
        
        ans += leaveDay - arriveDay + 1;

        
    return ans;


    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值