Common Character Count
Description
Given two strings, find the number of common characters between them.
Example
For s1 = "aabcc"
and s2 = "adcaa"
, the output should be
commonCharacterCount(s1, s2) = 3
.
Strings have 3
common characters - 2
“a”s and 1
“c”.
Input/Output
-
[execution time limit] 4 seconds (js)
-
[input] string s1
A string consisting of lowercase latin letters a-z
.
Guaranteed constraints:
1 ≤ s1.length ≤ 15
.
- [input] string s2
A string consisting of lowercase latin letters a-z
.
Guaranteed constraints:
1 ≤ s2.length ≤ 15
.
- [output] integer
[JavaScript (ES6)] Syntax Tips
1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}
Solution
1
2
3
4
5
6
7
8
9
10
11
function commonCharacterCount(s1, s2) {
var count = 0;
for(var i = 0; i < s1.length; i++) {
var j = s2.indexOf(s1[i]);
if(j>=0){
count++;
s2 = s2.replace(s1[i],'');
}
}
return count;
}