Sponsored
Sponsored
This approach involves treating each character of the column title string as a digit in a base-26 number system. We iterate over the string from left to right, calculating its contribution to the overall number at each step by multiplying with an appropriate power of 26.
Time Complexity: O(n), where n is the length of the column title.
Space Complexity: O(1), as no additional space is used that scales with input size.
1class Solution {
2 public int titleToNumber(String columnTitle) {
3 int result = 0;
4 for (char c : columnTitle.toCharArray()) {
5 result = result * 26 + (c - 'A' + 1);
6 }
7 return result;
8 }
9 public static void main(String[] args) {
10 Solution solution = new Solution();
11 System.out.println(solution.titleToNumber("ZY"));
12 }
13}
In Java, we achieve the same result using a loop to iterate over each character in the input string. We calculate the value using base-26 logic, accumulating the result.
This approach uses recursion to compute the column number. Starting from the first character, the function recursively converts the rest of the string and adds the current character's contribution by treating it as a digit in a 26-based number system. This implements a divide-and-conquer strategy.
Time Complexity: O(n)
Space Complexity: O(n), due to recursion stack space.
1
In the Python recursive solution, we define a helper function that recursively computes the column number by processing one character at a time, using recursion to handle the rest.