You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.
Example 1:
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation:
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Example 2:
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation:
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
Note:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
All strings contain lowercase English letters only.
Solution:
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode.AskGif.Easy.Array
{
public class CountCharactersSoln
{
public int CountCharacters(string[] words, string chars)
{
var available = new Dictionary<char, int>();
for (int i = 0; i < chars.Length; i++)
{
if (available.ContainsKey(chars[i]))
{
available[chars[i]]++;
}
else
{
available.Add(chars[i], 1);
}
}
int sum = 0;
for (int i = 0; i < words.Length; i++)
{
var temp = new Dictionary<char,int>(available);
bool possible = true;
for (int j = 0; j < words[i].Length; j++)
{
if (temp.ContainsKey(words[i][j])){
temp[words[i][j]]--;
if (temp[words[i][j]] == 0)
{
temp.Remove(words[i][j]);
}
}
else
{
possible = false;
break;
}
}
if (possible)
{
sum += words[i].Length;
}
}
return sum;
}
}
}
Time Complexity: O(n)
Space Complexity: O(n)
Unit Tests:
using LeetCode.AskGif.Easy.Array;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingUnitTest.Easy.Array
{
[TestClass]
public class CountCharactersSolnTests
{
[TestMethod]
public void CountCharactersSoln_First()
{
var words = new string[] { "cat", "bt", "hat", "tree" };
var chars = "atach";
var expected = 6;
var res = new CountCharactersSoln().CountCharacters(words, chars);
Assert.AreEqual(expected, res);
}
[TestMethod]
public void CountCharactersSoln_Second()
{
var words = new string[] { "hello", "world", "leetcode" };
var chars = "welldonehoneyr";
var expected = 10;
var res = new CountCharactersSoln().CountCharacters(words, chars);
Assert.AreEqual(expected, res);
}
}
}



