The trick here is to name the state correctly, then let the implementation follow. For 717. 1-bit and 2-bit Characters, the solution in this repository is mainly a bit manipulation solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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: bit manipulation.
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are isOneBitCharacter.
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:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
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: 0 ms, faster than 100.00% of C++ online submissions for 1-bit and 2-bit Characters.
02//Memory Usage: 8.7 MB, less than 100.00% of C++ online submissions for 1-bit and 2-bit Characters.
03
04class Solution {
05public:
06 bool isOneBitCharacter(vector<int>& bits) {
07 //if there are two or more "0" in the vector,
08 //all bits before(including) the 2nd last "0" can be ignored
09 vector<int> zero = {0};
10 vector<int>::iterator it = find_end(bits.begin(), bits.end()-1, zero.begin(), zero.end());
11
12 //if there are two or more "0"
13 if(it != bits.end()-1){
14 cout << bits.end() - it - 1 << endl;
15 //bits.end() - it: the length from 2nd last "0"
16 //bits.end() - it - 1: the length from the next bit of 2nd last "0"
17 //if the remaining string's length is odd,
18 //that means there will be a "0" not paired to other bits
19 return (bits.end() - it - 1)%2 != 0;
20 }
21
22 return bits.size()%2 != 0;
23 }
24};
Cost