Excel Sheet Column Number
LeetCode 171 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnTitle = "A"
Output: 1
Example 2:
Input: columnTitle = "AB"
Output: 28
Example 3:
Input: columnTitle = "ZY"
Output: 701
Constraints:
-
1 <= columnTitle.length <= 7 -
columnTitleconsists only of uppercase English letters. -
columnTitleis in the range["A", "FXSHRXW"].
Topics: Math, String
Approachβ
Mathematicalβ
Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.
Problems with clear mathematical structure, counting, number properties.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 76 ms)β
| Metric | Value |
|---|---|
| Runtime | 76 ms |
| Memory | 36 MB |
| Date | 2022-02-22 |
public class Solution {
public int TitleToNumber(string s) {
int result=0, len = s.Length;
for (int i = 0; i <len ; i++)
{
result = (result*26) + (s[i]-'A'+1);
}
return result;
}
}
π 2 more C# submission(s)
Submission (2022-02-22) β 103 ms, 36.5 MBβ
public class Solution {
public int TitleToNumber(string s) {
int result=0;
for (int i = 0; i <s.Length ; i++)
{
result = (result*26) + (s[i]-'A'+1);
}
return result;
}
}
Submission (2018-03-30) β 336 ms, N/Aβ
public class Solution {
public int TitleToNumber(string s) {
int result=0;
for (int i = 0; i <s.Length ; i++)
{
result = (result*26) + (s[i]-'A'+1);
}
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.