法一、直接暴力枚举
class Solution { public: bool check(string time,string res){ for(int i = 0;i < 5;i++){ if(time[i] == res[i] || time[i] == '?') continue; return false; } return true; } string maximumTime(string time) { for(int i = 23;i >= 0;i--){ for(int j = 59;j >= 0;j--){ char res[10]; sprintf(res,"%02d:%02d",i,j); if(check(time,res)) return res; } } return ""; } };
实质就是正则表达式匹配,从后往前暴力枚举,查看是否匹配。
学习sprintf 的用法
法二、直接模拟
class Solution { public: string maximumTime(string time) { if(time[0] == '?' ){ if(time[1] == '0' || time[1] == '1'||time[1] == '2' || time[1] == '3' || time[1] == '?' ) time[0] = '2'; else time[0] = '1'; } if(time[1] == '?'){ if(time[0] == '2') time[1] = '3'; else time[1] = '9'; } if(time[3] == '?' ) time[3] = '5' ; if(time[4] == '?' ) time[4] = '9' ; return time; } };