I have two strings, string1 and string2. I want to check if string1 can be made up of characters in string2 (without repeating characters”). For instance, if string1 is “tool” and string2 is “atoll”, the function will return false. If string1 is “touch” and string2 is “chetoudce”, it will return true.
What is the most efficient way to do this in Javascript? I was thinking of using indexOf and then removing the characters that are used from string2 to build string1, but I think creating this auxiliary string might have performance issues.
edit: I made this based on the first response, here it is:
function isSubsetOf(a, b){
if(a.length > b.length){
return false;
}
while(a.length > 0){
var letter = a.substr(0, 1),
re = new RegExp(a.substr(0, 1), 'g'),
a_count = (a.match(re)||[]).length,
b_count = (b.match(re)||[]).length;
if(a_count > b_count){
return false;
}
a = a.replace(re, '');
}
return true;
}
First, count the characters in each string. Then, if the superstring has greater than or equal numbers of each character than the substring, return true.
O(m+n), for m and n are the sizes of the substring and superstring.
Example: