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

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

知识点1

区间求交问题,已知我们的区间1:[a,b]区间2:[c,d],那么区间1区间2有交集部分的长度为多少呢?
我们有如下公式:max{0,min(b,d) - max(a,c) + 1}

知识点2

sscanf()函数

下面是 sscanf() 函数的声明。

int sscanf(const char *str, const char *format, ...)
s.c_str()这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string对象转换成c中的字符串样式。
这里就先记住,以后如果碰到相关的数据就这么处理

思路
  • 那么本题我们先分别求出A的起始天数和A的到达天数,B的起始天数和B的到达天数
    • 要计算天数,我们可以定义一个辅助函数
  • 随后我们利用如上公式即可完成
class Solution {
public:
    //求解日期问题,我们基本都会先定义这么一个数组
    int months[13] = {0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    //辅助函数,用于将日期转化为天数
    int get(string s){
        int res = 0;
        int m,d;
        sscanf(s.c_str(),"%d-%d",&m,&d);//这个trick要记住呀!!!
        for(int i = 1; i < m; i++) res += months[i];
        return res + d;
    }


    int countDaysTogether(string arriveAlice, string leaveAlice, string arriveBob, string leaveBob) {
        int a = get(arriveAlice), b = get(leaveAlice);
        int c = get(arriveBob), d = get(leaveBob);

        return max(0,min(b,d) - max(a,c) + 1);
    }
};

posted @ 2022-09-26 21:18  Sheldon2  阅读(64)  评论(0)    收藏  举报