Leetcode 問題:
您將獲得一個以 hh:mm 格式表示時間的字串。一些數字是空白的(用?表示)。填寫?此字串表示的時間是可能的最大值。最長時間:23:59,最短時間:00:00。您可以假設輸入字串始終有效。
uj5u.com熱心網友回復:
您可以使用String.replace的替換功能。傳入的第二個引數是 ? 的位置,因此可以使用它在陣列中查找該位置的最大值。
const maxValues = ["2", "3", ":", "5", "9"];
const maxTime = (time) => time.replace(/\?/g, (s, p, str) => {
if (p === 1 && str[0] !== '2' && str[0] !== '?' ) {
return '9';
}
return maxValues[p];
});
console.log(maxTime("?1:1?"))
console.log(maxTime("??:??"))
console.log(maxTime("11:11"))
console.log(maxTime("1?:?1"))
uj5u.com熱心網友回復:
maxTime = (time) => {
const timeArr = time.split(":");
let hr = timeArr[0];
let mn = String(timeArr[1]);
if (mn.includes("?")) {
const mnArr = mn.split("");
if (mnArr[0] === "?" && mnArr[1] === "?") {
mn = "59";
} else if (mnArr[0] === "?") {
mn = "5" mnArr[1];
} else if (mnArr[1] === "?") {
const temp = mnArr[0] === "5" ? "9" : "0";
mn = mnArr[0] temp;
}
}
if (hr.includes("?")) {
const hrArr = hr.split("");
if (hrArr[0] === "?" && hrArr[1] === "?") {
hr = "23";
} else if (hrArr[0] === "?") {
hr = "2" hrArr[1];
hr = Number(hr) <= 24 ? "1" hrArr[1] : hr;
} else if (hrArr[1] === "?") {
const temp = hrArr[0] === "2" ? "3" : "9";
hr = hrArr[0] temp;
}
}
return `(${time}) => ${hr}:${mn}`;
}
uj5u.com熱心網友回復:
這不是一個非常優雅的解決方案,但它解決了我在回復 James 時指出的問題,其中 HH 中的 send H 可以是 9 或 3,具體取決于時間。這也是不同的,但也是有效的。
maxTime = (strTime) => {
let [...str] = strTime;
if (str[0] == "?") { str[0] = "2"; }
if (str[1] == "?" && str[0] < "2") { str[1] = "9"; } else { str[1] = "3"; }
if (str[3] == "?") { str[3] = "5"; }
if (str[4] == "?") { str[4] = "9"; }
return str.join('');
}
console.log(maxTime("?2:22")); // 22:22
console.log(maxTime("2?:22")); // 23:22
console.log(maxTime("22:?2")); // 22:52
console.log(maxTime("22:2?")); // 22:29
console.log(maxTime("0?:??")); // 09:59
console.log(maxTime("1?:??")); // 19:59
console.log(maxTime("??:??")); // 23:59
或回圈
const max = "29:59";
maxTime = (strTime) => {
let [...str] = strTime;
for (x = 0; x < 5; x ) { if (strTime[x] == "?") { str[x] = max[x]; }}
if (str[0] == "2" && strTime[1] == "?") { str[1] = "3"; }
return str.join('');
}
console.log(maxTime("?2:22")); // 22:22
console.log(maxTime("2?:22")); // 23:22
console.log(maxTime("22:?2")); // 22:52
console.log(maxTime("22:2?")); // 22:29
console.log(maxTime("0?:??")); // 09:59
console.log(maxTime("1?:??")); // 19:59
console.log(maxTime("??:??")); // 23:59
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507071.html
標籤:javascript
上一篇:reactjs如何區分組件實體?
