This is one of those problems where the clean idea matters more than the amount of code. For 1576. Replace All question mark's to Avoid Consecutive Repeating Characters, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. 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?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are modifyString, chosen.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- 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:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
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: 4 ms, faster than 25.81% of C++ online submissions for Replace All ?'s to Avoid Consecutive Repeating Characters.
02//Memory Usage: 6.1 MB, less than 60.58% of C++ online submissions for Replace All ?'s to Avoid Consecutive Repeating Characters.
03class Solution {
04public:
05 string modifyString(string s) {
06 int n = s.size();
07
08 for(int i = 0; i < n; ++i){
09 if(s[i] == '?'){
10 vector<bool> chosen(26, false);
11
12 if(i-1 >= 0){
13 chosen[s[i-1]-'a'] = true;
14 }
15
16 if(i+1 < n && s[i+1] != '?'){
17 chosen[s[i+1]-'a'] = true;
18 }
19
20 for(int j = 0; j < 26; ++j){
21 if(!chosen[j]){
22 s[i] = 'a'+j;
23 break;
24 }
25 }
26 }
27 }
28
29 return s;
30 }
31};
Cost