string inside a string - hackerrank
Hackerrank- String
by Samar Pattanayak
JavaScript
var str = "hackerworld";
var defstr = "hackerrank";
var firstIndex = 0;
var count = 0;
var resultIndex = 0;
for (var i = 0; i < defstr.length; i++) {
var reg = defstr[i];
//console.log(reg);
var arr = [];
var diffarr = [];
for (var j = 0; j < str.length; j++) {
if (str[j] == reg) {
arr.push(j);
}
}
var mapObj = new Map();
//console.log(arr);
for (let va of arr) {
mapObj.set(va, va - firstIndex);
}
//console.log(mapObj)
var small = 0;
var arrValue = [];
for (var [key, value] of mapObj.entries()) {
if (value >= 0) {
arrValue.push(value);
}
}
//console.log("arrValue", arrValue);
if (arrValue.length > 0) {
small = arrValue.reduce((y, z) => {
if (y < z) {
return y;
} else {
return z;
}
});
}
//console.log("small", small);
for (var [key, value] of mapObj.entries()) {
if (value == small) {
firstIndex = key;
str = str.substr(0, firstIndex) + '*' + str.substr(firstIndex + 1);
//console.log(str);
if (firstIndex >= resultIndex) {
count++;
} else {
console.log("No")
}
}
}
//console.log("firstIndex", firstIndex);
//console.log("*************")
}
//console.log(count);
if (count == defstr.length) {
console.log("YES");
} else {
console.log("NO")
}