示例 如果域是:
1.google.com
2.go.google.com
3.pro.go.google.com
輸入網址是:
hello.go.google.com //將回傳域 2(go.google.com 因為它是最近的)
abc.hello.go.google.com // 將回傳域 2(go.google.com 因為它是最近的)
qwert.pro.go.google.com // 將回傳域 3(pro.go.google.com 因為它是最近的)
pro1.go.google.com // 將回傳域 2(go.google.com 因為它是最近的)
xyz.google.com // 將回傳域 1(google.com 因為它是最近的)
我創建了一個蠻力演算法,它正在作業,但在一種情況下它失敗了:
輸入 url : xgo.google.com //回傳域 2 即 go.google.com 但應回傳域 1 即 google.com
下面是我試過的源代碼:
const domainArr = ["google.com", "go.google.com", "pro.go.google.com"];
const pureHostName = "xgo.google.com";
let maxLength = 0;
let selectedDomain = "";
for (let i = 0; i < domainArr.length; i ) {
const domain = domainArr[i];
if (pureHostName.includes(domain)) {
if (i === 0) {
maxLength = domain.length;
selectedDomain = domain;
}
if (domain.length > maxLength) {
maxLength = domain.length;
selectedDomain = domain;
}
}
}
console.log("selectedDomain--->", selectedDomain); //returning go.google.com instead of google.com
uj5u.com熱心網友回復:
嗯,首先是根據每個域的子域長度對域進行排序,然后將較長的子域數放在首位,然后再放置較短的子域數。
然后,逐個檢查每個域。如果當我們在迭代中將句點字符添加到當前域時,手頭的當前測驗用例完全匹配或具有子域,則我們找到了匹配項。否則,對其他可用域繼續相同的測驗。
const domainArr = ["google.com", "go.google.com", "pro.go.google.com"];
const testCases = [
"hello.go.google.com",
"abc.hello.go.google.com",
"qwert.pro.go.google.com",
"pro1.go.google.com",
"xyz.google.com"
];
domainArr.sort((a, b) => b.split('.').length - a.split('.').length);
for (let i = 0; i < testCases.length; i) {
let match = 'No match found!';
for (let j = 0; j < domainArr.length; j) {
if (testCases[i] == domainArr[j] || testCases[i].includes("." domainArr[j])) {
match = domainArr[j];
break;
}
}
console.log(testCases[i] " => " match);
}
uj5u.com熱心網友回復:
根據您的描述,您需要匹配domainArr. 因此,您需要更新您的代碼,以便在找到匹配的域時停止并洗掉額外的if陳述句:
const domainArr = ["google.com", "go.google.com", "pro.go.google.com"];
const pureHostName = "xgo.google.com";
let maxLength = 0;
let selectedDomain = "";
for (let i = 0; i < domainArr.length; i ) {
const domain = domainArr[i];
if (pureHostName.includes(domain)) {
maxLength = domain.length;
selectedDomain = domain;
//Add this
break;
}
}
console.log("selectedDomain--->", selectedDomain);
讓我知道這是否能解決您的問題
uj5u.com熱心網友回復:
這在技術上與 nice_dev 的答案相似,但它提供了不同的 API。您將域串列提供給一個函式,它對它們進行排序(淺克隆)并回傳一個函式,該函式接受一個域并找到父域(如果它們都不匹配,則回傳一個空字串。)
const parentDomain = (domains) => {
const sorted = [...domains] .sort (
(a, b) => b .split ('.') .length - a .split ('.') .length
)
return (domain) => sorted .find ((d) => domain .endsWith ('.' d)) || ''
}
const googleDomain = parentDomain (["google.com", "go.google.com", "pro.go.google.com"])
const testCases = ['hello.go.google.com', 'abc.hello.go.google.com', 'qwert.pro.go.google.com',
'pro1.go.google.com', 'xyz.google.com', 'xgo.google.com']
testCases .forEach (url => console .log (`"${url}" ==> "${googleDomain (url)}"`))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/517826.html
