zl程序教程

您现在的位置是:首页 >  其他

当前栏目

LeetCode·每日一题·2437. 有效时间的数目·模拟

LeetCode模拟 时间 有效 每日 数目
2023-09-27 14:26:29 时间

作者:小迅
链接:https://leetcode.cn/problems/number-of-valid-clock-times/solutions/2262448/mo-ni-zhu-shi-chao-ji-xiang-xi-by-xun-ge-r1ox/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

题目

 

示例

 

思路

题意 -> 给定一个时间字符串,枚举有效时间的个数

两种方法

  • 根据题目意思直接枚举,列举所有时间,然后与给定时间字符串逐一比较是否满足要求。
  • 还可以分类讨论存在的有效时间,因为给定 ? 号的位置存在多少有效时间是固定的,可以讨论不同 ? 号位置情况,直接得出有效时间个数

代码注释超级详细

代码

//直接枚举
bool check(char *time, char *str)//比较任意时间节点与给定时间字符串是否匹配
{
    for (int i = 0; i < 5; i++) {//比较每一个位置
        //如果当前位置不一样还不存在 ? 号,肯定不匹配,以此类推
        if (time[i] != '?' && time[i] != str[i]) {
            return false;
        }
    }
    return true;
}

int countTime(char * time){
    int res = 0;
    char str[6] = "00:00";//时间节点字符串
    for (int h = 0; h < 24; h++) {
        for (int m = 0; m < 60; m++) {//枚举所有时间节点
            sprintf(str, "%02d:%02d", h, m);//构造时间节点字符串,方便比较
            if (check(time, str)) {//比较每一个时间与给定时间字符串
                res++;
            }
        }
    }
    return res;
}

作者:小迅
链接:https://leetcode.cn/problems/number-of-valid-clock-times/solutions/2262448/mo-ni-zhu-shi-chao-ji-xiang-xi-by-xun-ge-r1ox/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
//分类讨论
int countTime(char * time){
    int left = 1;//时钟可能存在个数
    int right = 1;//分钟可能存在个数
    //分类讨论不同位置时钟存在个数,因为时钟存在2,所有情况更多
    if(time[0] == '?' && time[1] == '?')
        left = 24;
    else if(time[0] == '?' && time[1]-'0' == 4 & time[3]-'0' == 0)
        left = 3;
    else if(time[0] == '?' && time[1]-'0' == 4 & time[3]-'0' != 0)
        left = 2;
    else if(time[0] == '?' && time[1]-'0' < 4)
        left = 3;
    else if(time[0] == '?' && time[1]-'0' > 4)
        left = 2;
    else if(time[0] == '2' && time[1] == '?')
        left = 4;
    else if(time[0] != '2' && time[1] == '?')
        left =10;
    //分类讨论不同位置分钟存在个数
    if(time[3] == '?' && time[4] == '?')
        right = 60;
    else if(time[3] == '?')
        right = 6;
    else if(time[4] == '?')
        right = 10;
    return left * right;
}

作者:小迅
链接:https://leetcode.cn/problems/number-of-valid-clock-times/solutions/2262448/mo-ni-zhu-shi-chao-ji-xiang-xi-by-xun-ge-r1ox/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。