Problem Description
Given a string columnTitle representing a column title as it appears in an Excel sheet, return its corresponding column number. For example, A maps to 1, B maps to 2, ..., Z maps to 26, AA maps to 27, AB maps to 28, and so on.
Key Insights
- The problem is similar to converting a base-26 numeral system to a decimal number.
- Each character in the string represents a digit value where 'A' equals 1, 'B' equals 2, ..., and 'Z' equals 26.
- Iteratively multiply the accumulated result by 26 and add the numeric value of the current character.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the columnTitle string.
Space Complexity: O(1) due to the use of a constant amount of additional space.
Solution
The solution treats the given column title as a number in base-26. For each character in the string, the algorithm converts the character to its corresponding numeric value (A=1, B=2, …, Z=26) by adjusting with the ASCII value. It then accumulates the result by multiplying the current result by 26 (reflecting a shift in the numeral system) and adding the current digit. This ensures that the overall runtime scales linearly with the length of the input string and uses constant space.