Problem Name: 1160. Find Words That Can Be Formed by Characters
Problem Link: https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/description/
Difficulty: Easy
Tag: Array | String | Hash Table
Language: C# | C++
OJ: LeetCode
Algorithm:
1.Initialize an array named store with 26 elements, representing the lowercase English alphabet. This array is used to store the count of each character in the input string chars.
2.Iterate through each character in the chars string and increment the corresponding count in the store array.
3.Initialize a variable named answer to 0. This variable will store the final count of characters that can be formed from the given words.
4.Iterate through each word in the array words:
a. Inside the loop, initialize a new array named temp with 26 elements. This array is used to store the count of each character in the current word.
b. Set a boolean variable flag to true. This flag will be used to check if the current word can be formed using the characters in the chars string.
c. Iterate through each character in the current word and increment the corresponding count in the temp array.
d. Print the current word using Console.WriteLine(word).
e. Iterate through each index (representing a character) from 0 to 25.
If the count of the current character in the store array is less than the count of the same character in the temp array, set flag to false and break the loop.
f. If the flag is still true after the inner loop, increment the answer variable by the length of the current word. This means that the current word can be formed using the characters in the chars string.
5.Return the final value of the answer variable.
Code(C#)
public class Solution
{
public int CountCharacters(string[] words, string chars)
{
int[] store = new int[26];
int answer = 0;
for (int i = 0; i < chars.Length; i++)
store[chars[i] - 'a']++;
foreach(var word in words)
{
int[] temp = new int[26];
bool flag = true;
for (int i = 0; i < word.Length; i++)
temp[word[i] - 'a']++;
Console.WriteLine(word);
for (int i = 0; i < 26; i++)
if (store[i] < temp[i])
{
flag = false;
break;
}
if (flag) answer += word.Length;
}
return answer;
}
}
Code(C++)
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
//Upcoming......
}
};