Search This Blog

2023/05/27

Longest Common String -Unefficient Way

 function removeChar(str, startIndex, toRemove) {

var newString = ""
for (let i = 0; i < str.length; i++) {
if (i >= startIndex && i < startIndex + toRemove) {
continue
} else {
newString = newString + str[i]
}
}
return newString
}

function GetAllCombinations(s1) {
var s1Word = new Set()
var lenofs1 = s1.length;
var visited = []

for (let i = 1; i < lenofs1; i++) {
for (let j = 0; j < lenofs1 - i + 1; j++) {
var str = removeChar(s1, j, i)

if (visited.includes(str) == false) {
visited.push(str)

//s1Word.add({ "string": str, "i": i, "j": j, "source": s1 })
s1Word.add(str)

if (str.length > 1) {
let rec = GetAllCombinations(str)
s1Word = new Set([...rec, ...s1Word])
}
}


}
}
return s1Word
}


function commonChild(s1, s2) {
let res1 = GetAllCombinations(s1)
const array1 = Array.from(res1);

var res2 = GetAllCombinations(s2)
const array2 = Array.from(res2);

var common = []
for (let i = 0; i < array1.length; i++) {
if (array2.includes(array1[i])) {
common.push(array1[i])
}
}

var maxLenth = Number.NEGATIVE_INFINITY
var maxStr = ""
for (let i = 0; i < common.length; i++) {
if (maxLenth < common[i].length) {
maxLenth = common[i].length
maxStr = common[i]
}
}

return maxStr.length

}



let s1 = "SHINCHAN", s2 = "NOHARAAA";
let res = commonChild(s1, s2)
console.log("Result", res)

No comments:

Post a Comment