LeetCode·每日一题·2437. 有效时间的数目·模拟
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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关文章
- 【LeetCode】填充每个节点的下一个右侧节点指针 [M](二叉树遍历)
- 【LeetCode】天际线问题 [H](模拟)
- 【LeetCode】区间和的个数
- LeetCode_前缀和_哈希表_困难_2488.统计中位数为 K 的子数组
- LeetCode_动态规划_中等_213.打家劫舍 II
- leetcode 222. 完全二叉树的节点个数
- LeetCode·每日一题·1638. 统计只差一个字符的子串数目·模拟·
- LeetCode·每日一题·1806.还原排列的最少操作步数·模拟
- LeetCode·每日一题·2023.至少在两个数组中出现的值·模拟
- LeetCode·每日一题·1764.通过连接另一个数组的子数组得到一个数组·模拟
- LeetCode·每日一题·1945.字符串转化后的各位数组之和·模拟
- LeetCode·每日一题·775.全局倒置与局部倒置·模拟
- LeetCode·每日一题·1662.检查两个字符串数组是否相等·模拟
- LeetCode·每日一题·1768.交替合并字符串·模拟
- LeetCode·每日一题·1790.仅执行一次字符串交换能否使两个字符串相等·模拟
- LeetCode·每日一题·1784.检查二进制字符串字段·模拟
- LeetCode·每日一题·面试题 01.08. 零矩阵· 模拟
- LeetCode·71.简化路径·栈模拟
- LeetCode·每日一题·1598.文件夹操作日志收集器·栈模拟
- LeetCode·每日一题·1656.设计有序流·模拟
- LeetCode·每日一题·1417.重新格式化字符串·模拟
- LeetCode·每日一题·640.求解方程·模拟构造
- LeetCode·每日一题·636.函数的独占时间·栈模拟
- LeetCode 017 4Sum
- [LeetCode] 849. Maximize Distance to Closest Person 最大化最近人的距离
- [LeetCode] 78. Subsets 子集合
- leetcode 92 翻转链表II