Let's make this one less mysterious. For 1160. Find Words That Can Be Formed by Characters, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are countCharacters, count.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 64 ms, faster than 96.69% of C++ online submissions for Find Words That Can Be Formed by Characters.
02//Memory Usage: 17.4 MB, less than 100.00% of C++ online submissions for Find Words That Can Be Formed by Characters.
03
04class Solution {
05public:
06 int countCharacters(vector<string>& words, string chars) {
07 vector<int> count(26), tmp_count(26);
08 bool isGood;
09 int ans = 0;
10
11 for(char c : chars){
12 count[c - 'a']++;
13 }
14
15 for(string word : words){
16 fill(tmp_count.begin(), tmp_count.end(), 0);
17 isGood = true;
18 for(char c : word){
19 tmp_count[c - 'a']++;
20 if(tmp_count[c - 'a'] > count[c - 'a']){
21 isGood = false;
22 break;
23 }
24 }
25 if(isGood){
26 ans += word.size();
27 }
28 }
29
30 return ans;
31 }
32};
Cost