将给定的长度为五的字符串表示为HH:MM格式的时间。字符串中可能包含一些“?”我们必须用任何数字替换它们,以使结果成为有效的时间,且可能是最大的可能时间。此外,给定的字符串数字将是有效的,并且“:”将出现在字符串的确切位置。我们将首先使用蛮力法,然后使用高效方法。
示例示例
输入 1
'Given string: 12:5?
Output: 12:59
Explanation
的中文翻译为:解释
我们只有一个位置需要填补,而我们能够获得的最大时间是12:59。
输入2
'Given string: ?0:?9
Output: 20:59
Explanation
的中文翻译为:解释
我们这里有两个空槽,首先,我们将专注于小时部分,我们有三个选择0、1和2来填充。对于分钟部分,我们有从0到5的选择,为了最大化,我们可以填充5。
方法
我们已经看过了例子,现在让我们来看看我们可能面临的不同类型的情况 −
我们有两部分字符串,小时部分和分钟部分。
小时部分的范围是0到23,分钟部分的范围是0到59。
小时部分还有更多的情况−
‘x?’ 其中 x 可以是 0、1 和 2。对于 0,我们可以选择 0 作为最佳选择,对于 1,我们可以选择 9 作为最佳选择,对于 2,我们可以选择 3 作为最佳选择。
'?x',其中x的范围可以是0到9。如果x在0到3的范围内,我们可以用2替换它,否则1将是最好的。
‘??’ 因为我们需要最大化,所以我们将其替换为 23。
会议记录,部分还有进一步的案例 −
‘x?’其中x可以在0到5的范围内。9将是我们最好的选择来替代‘?’。
‘?x’其中x可以在0到9的范围内。5将是我们最好的选择来替换‘?’。
“??”,因为我们必须最大化,然后我们将其替换为 59。
让我们来看看实现上述步骤的代码 -
Example
的中文翻译为:例子
'#include <iostream>
using namespace std;
// function to replace hours
string replaceHours(string s){
if(s[0] == '?' && s[1] == '?'){
//Both hour characters are '?'
// replace with the maximum hour we can achieve
s[0] = '2';
s[1] = '3';
}
else if(s[0] == '?'){
// if the second number of hours is in the range 0 to 3
// replace by 2
if(s[1] < 4){
s[0] = '2';
}
else{
s[0] = '1'; // otherwise replace by one
}
}
else if(s[1] == '?'){
// if the first character is '2' we can go only upto 3
if(s[0] == '2'){
s[1] = '3';
}
else{
s[1] = '9'; // else we can go for 9
}
}
return s;
}
// function to replace minutes
string replaceMinutes(string s){
if(s[3] == '?' && s[4] == '?'){
// both minutes characters are '?'
// replace with maximum minutes we can acheive
s[3] = '5';
s[4] = '9';
}
else if(s[3] == '?'){
// we can maximum get 5 here
s[3] = '5';
}
else if(s[4] == '?'){
// we can get maximum 9 here
s[4] = '9';
}
return s;
}
int main(){
string str = "2?:3?"; // given string
// calling the function for updation of the minutes
str = replaceMinutes(str);
// calling to the function for updation of the hours
str = replaceHours(str);
// printing the final answer
cout<<"The maximum time we can get by replacing ? is: "<< str<<endl;
return 0;
}
输出
'The maximum time we can get by replacing ? is: 23:39
时间和空间复杂度
上述代码的时间复杂度为O(1)或常数,因为我们没有使用任何循环或递归调用,只是检查了if-else条件
上述代码的空间复杂度为O(1),因为我们没有使用任何额外的空间。此外,对于该函数,我们传递的字符串大小始终是固定的5。
注意:为了使代码更美观或易读,可以使用switch语句,它们不会影响时间或空间复杂度,并且会使阅读更高效。
此外,回溯和重新检查是一种解决方案,但这将检查每种情况,并且在这里实施起来效率不高。
结论
在本教程中,我们得到了一个以24小时制表示时间的字符串。字符串中有一些“?”需要替换,以获得有效的最大时间,并且保证字符串中的字符始终指向有效的时间。我们使用了if-else条件和两个函数来替换“?”为适当的情况。由于我们没有使用任何循环或递归函数,上述代码的时间和空间复杂度是恒定的。