Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Wildcard matching of string JavaScript
We are required to write a JavaScript function that accepts two strings and a number n. The function matches the two strings i.e., it checks if the two strings contains the same characters. The function should return true if both the strings contain the same character irrespective of their order or if they contain at most n different characters, otherwise the function should return false.
Let's write the code for this function ?
Example
const str1 = 'first string';
const str2 = 'second string';
const wildcardMatching = (first, second, num) => {
let count = 0;
for(let i = 0; i < first.length; i++){
if(!second.includes(first[i])){
count++;
};
if(count > num){
return false;
};
};
return true;
};
console.log(wildcardMatching(str1, str2, 2));
console.log(wildcardMatching(str1, str2, 1));
console.log(wildcardMatching(str1, str2, 0));
Output
The output in the console will be ?
true true false
How It Works
The function iterates through each character in the first string and checks if it exists in the second string using includes(). If a character is not found, the count is incremented. When the count exceeds the allowed number of different characters (num), the function returns false.
Improved Version with Character Frequency
A more robust approach considers character frequencies to avoid counting duplicate mismatches:
const improvedWildcardMatching = (first, second, num) => {
const firstChars = new Set(first);
const secondChars = new Set(second);
let mismatchCount = 0;
// Check characters in first string not in second
for(let char of firstChars) {
if(!secondChars.has(char)) {
mismatchCount++;
}
}
return mismatchCount <= num;
};
console.log(improvedWildcardMatching('abc', 'def', 3)); // true
console.log(improvedWildcardMatching('abc', 'def', 2)); // false
console.log(improvedWildcardMatching('hello', 'world', 8)); // true
true false true
Conclusion
Wildcard matching in JavaScript can be implemented by counting character differences between strings. The improved version using Sets provides better performance and avoids duplicate character counting.
