我正在嘗試解決 CodeWars kata Scrambles:
如果部分字符可以重新排列以匹配,則完成
scramble(str1, str2)回傳的函式,否則回傳。truestr1str2false筆記:
- 僅使用小寫字母 (az)。不包含標點符號或數字。
- 需要考慮性能。
例子
scramble('rkqodlw', 'world') ==> True scramble('cedewaraaossoqqyt', 'codewars') ==> True scramble('katas', 'steak') ==> False
我的代碼沒有通過這個 kata 中的所有測驗。顯然,當str2重復一個不在str1.
例如,這是錯誤之一:
輸入的錯誤答案:
s1='scriptjavx' s2='javascript': 預計
true相等false
這是我的解決方案
function scramble(str1, str2) {
let sameChar = ""
for (char of str2) {
if (str1.includes(char)) {
sameChar = char
}
}
if (str2 == sameChar)
return true
else
return false;
}
你能告訴我如何解決它嗎?
uj5u.com熱心網友回復:
問題是str1.includes(char)仍然允許在同一地點再次找到找到的字符。例如,如果str2是“aa”并且str1是“a”,您可以看到它是如何出錯的。那個單一的“a”str1應該只為一場比賽服務一次,而不是兩次。
一個解決方案是保持每個字符的計數:
function scramble(str1, str2) {
if (str2.length > str1.length) return false;
const counts = {};
for (let c of str1) {
counts[c] = (counts[c] || 0) 1
}
for (let c of str2) {
if (!counts[c]) return false;
counts[c]--;
}
return true;
}
uj5u.com熱心網友回復:
你做了很好的邏輯,但你需要同時測驗它,你只測驗了str2,我添加了相同的測驗str1
function scramble(str1, str2) {
let sameChar1 = ""
let sameChar2 = ""
for (char of str1) {
if (str2.includes(char)) {
sameChar1 = char
}
}
for (char of str2) {
if (str1.includes(char)) {
sameChar2 = char
}
}
if (str1 == sameChar1 && str2 == sameChar2)
return true
else
return false;
}
console.log(scramble('scriptjavx', 'javascript'))
uj5u.com熱心網友回復:
您可以創建一個副本str1并洗掉每個匹配的字符,這樣它就不會被多次匹配,如下所示:
function scramble(str1, str2) {
const str1Copy = [ ...str1 ];
for (const char of str2) {
const idx = str1Copy.indexOf(char);
if (idx !== -1) {
str1Copy.splice(idx, 1);
}
else {
return false;
}
}
return true;
}
console.log(scramble("scriptjavx", "javascript")); // false
console.log(scramble("scriptjavxa", "javascript")); // true
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/517631.html
標籤:javascript功能
