I need to remove common letters from both the strings. But, some of the letters get removed.some of them not. In this example, a is common in both the strings.but not get removed. Could you tell the mistake what I did?
var a = "car"
var b = "karthic"
var c = a.length;
var d = b.length;
for (var i = 0; i < c; i ) {
for (var j = 0; j < d; j ) {
if (a[i] === b[j]) {
a = a.slice(0, i) a.slice(i 1);
b = b.slice(0, j) b.slice(j 1);
break;
}
}
}
console.log(a " " b);
CodePudding user response:
First find all common letters, then remove them from each string:
var a = "car"
var b = "karthic"
var c = a.length;
var d = b.length;
var commonLetters = [];
for (var i = 0; i < c; i ) {
for (var j = 0; j < d; j ) {
if (a[i] === b[j]) {
commonLetters.push(a[i]);
}
}
}
var regex = new RegExp('[' commonLetters.join('') ']', 'g')
a = a.replace(regex, '');
b = b.replace(regex, '');
console.log('A: ' a, 'B: ' b, commonLetters);
CodePudding user response:
You can convert both strings to a set, find the difference and then filter (include) any characters that are included in the difference.
Access to a Set is O(1) which is better than your (worst-case) O(n^2) loop. You will have to filter all of the characters in each string so this will be O(n) complexity as your base-case.
// Reusable
const strSet = (str) => new Set(str.split(''));
const setDiff = (a, b) => new Set(Array.from(a).filter(item => !b.has(item)));
const prune = (str, set) => str.split('').filter(x => set.has(x)).join('');
// Specific
const a = 'car', b = 'karthic';
const diff = setDiff(strSet(b), strSet(a));
const a1 = prune(a, diff), b1 = prune(b, diff);
console.log(`a1 = "${a1}"\nb1 = "${b1}"`);
CodePudding user response:
let a = "car"
let b = "karthic";
let resultA = a.split('').filter((elem) => b.indexOf(elem) == -1).join('');
let resultB = b.split('').filter((elem) => a.indexOf(elem) == -1).join('');
console.log(resultB);
console.log(resultA);
CodePudding user response:
Your loops are not taking the reduction of the string into consideration.
Here is your string at the beginning of the third outer for-loop:
var a="a" //length 1, 'a' is at index 0
var b="kathi" //length 5, 'a' is in index 1
When your algorithm reaches the third loop, your 'i' for-loop variable will point to index '2.' At that point, 'c' and 'r' are already removed from the variable 'a' leaving only the character 'a' in the string. This variable will be at index 0. So when your 'i' loop is looking at index '2,' it won't find anything.
console.log(a[2]) //undefined
console.log(b[5]) //undefined
You will need to modify your algorithm to take the new size length into consideration.
