Let's make this one less mysterious. For 1446. Consecutive 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?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are maxPower.
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: 12 ms, faster than 66.67% of C++ online submissions for Consecutive Characters.
02//Memory Usage: 6.8 MB, less than 100.00% of C++ online submissions for Consecutive Characters.
03class Solution {
04public:
05 int maxPower(string s) {
06 if(s.size() == 0) return 0;
07
08 int ans = 1; //need to initialize as 1, not 0!(imagine the case "j")
09 int cur = 1; //need to initialize as 1, not 0!
10
11 char last = s[0];
12 for(int i = 1; i < s.size(); i++){
13 if(s[i] == last){
14 cur++;
15 }
16
17 if(s[i] != last || i == s.size()-1){
18 ans = max(ans, cur);
19 cur = 1;
20 }
21
22 last = s[i];
23 }
24
25 return ans;
26 }
27};
Cost