Strings Construction
Description
Given two strings a
and b
, both consisting only of lowercase English letters, your task is to calculate how many strings equal to a
can be constructed using only letters from the string b
? Each letter can be used only once and in one string only.
Example
-
For
a = "abc"
andb = "abccba"
, the output should bestringsConstruction(a, b) = 2
.We can construct
2
stringsa = "abc"
using only letters from the stringb
. -
For
a = "ab"
andb = "abcbcb"
, the output should bestringsConstruction(a, b) = 1
.
Input/Output
-
[execution time limit] 4 seconds (js)
-
[input] string a
String to construct, containing only lowercase English letters.
Guaranteed constraints:
1 ≤ a.length ≤ 105
. -
[input] string b
String containing needed letters, containing only lowercase English letters.
Guaranteed constraints:
1 ≤ b.length ≤ 105
. -
[output] integer
- The number of strings
a
that can be constructed from the stringb
.
- The number of strings
[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
12
13
14
15
16
17
18
19
20
21
function stringsConstruction(a, b) {
var count = 0;
var finding = true;
var pos;
b = b.split("");
while (finding) {
for (var i = 0; i < a.length; i++) {
pos = b.indexOf(a[i]);
if (pos >= 0) {
b.splice(pos, 1);
} else {
finding = false;
break;
}
}
if (finding) {
count++;
}
}
return count;
}