Skip to content

Commit 8de2373

Browse files
Add No_171: Excel Sheet Column Number
1 parent c85a274 commit 8de2373

File tree

2 files changed

+104
-0
lines changed

2 files changed

+104
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'''
2+
3+
Description:
4+
5+
Given a column title as appear in an Excel sheet, return its corresponding column number.
6+
7+
For example:
8+
9+
A -> 1
10+
B -> 2
11+
C -> 3
12+
...
13+
Z -> 26
14+
AA -> 27
15+
AB -> 28
16+
...
17+
Example 1:
18+
19+
Input: "A"
20+
Output: 1
21+
Example 2:
22+
23+
Input: "AB"
24+
Output: 28
25+
Example 3:
26+
27+
Input: "ZY"
28+
Output: 701
29+
30+
'''
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
'''
2+
3+
Description:
4+
5+
Given a column title as appear in an Excel sheet, return its corresponding column number.
6+
7+
For example:
8+
9+
A -> 1
10+
B -> 2
11+
C -> 3
12+
...
13+
Z -> 26
14+
AA -> 27
15+
AB -> 28
16+
...
17+
Example 1:
18+
19+
Input: "A"
20+
Output: 1
21+
Example 2:
22+
23+
Input: "AB"
24+
Output: 28
25+
Example 3:
26+
27+
Input: "ZY"
28+
Output: 701
29+
30+
'''
31+
32+
33+
34+
class Solution:
35+
def titleToNumber(self, s: str) -> int:
36+
37+
if len(s) == 1:
38+
# base case
39+
return ord(s)-64
40+
41+
else:
42+
# general case
43+
return 26*self.titleToNumber( s[:-1] ) + self.titleToNumber( s[-1] )
44+
45+
46+
47+
# n : the length of input string s
48+
49+
## Time Complexity: O( n )
50+
#
51+
# The major overhead in time is the call depth of recursion, which is of O( n ).
52+
53+
## Space Complexity: O( n )
54+
#
55+
# The major overhead in space is to maintain call stack for recursion, which is of O( n ).
56+
57+
58+
59+
def test_bench():
60+
61+
test_data = ['A', 'AB', 'AZ', 'BA','ZY', 'ZZ','AAA']
62+
63+
for s in test_data:
64+
65+
n = Solution().titleToNumber(s)
66+
print(n)
67+
68+
return
69+
70+
71+
72+
if __name__ == '__main__':
73+
74+
test_bench()

0 commit comments

Comments
 (0)