A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 171. Excel Sheet Column Number, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. 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 titleToNumber.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- 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/**
02Given a column title as appear in an Excel sheet, return its corresponding column number.
03
04For example:
05
06 A -> 1
07 B -> 2
08 C -> 3
09 ...
10 Z -> 26
11 AA -> 27
12 AB -> 28
13 ...
14Example 1:
15
16Input: "A"
17Output: 1
18Example 2:
19
20Input: "AB"
21Output: 28
22Example 3:
23
24Input: "ZY"
25Output: 701
26**/
27
28//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Excel Sheet Column Number.
29//Memory Usage: 8.1 MB, less than 53.74% of C++ online submissions for Excel Sheet Column Number.
30
31class Solution {
32public:
33 int titleToNumber(string s) {
34 int ans = 0;
35 for(string::reverse_iterator r = s.rbegin(); r!=s.rend(); r++){
36 ans += (*r - 'A' + 1) * pow(26, (r - s.rbegin()));
37 }
38 return ans;
39 }
40};
Cost