less than 1 minute read

Problem

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
  • columnTitle consists only of uppercase English letters.
  • columnTitle is in the range ["A", "FXSHRXW"].

Solution

Logic

  1. 문자열에서 i번째(0-indexed)에 위치한 문자를 26의 (문자열 길이 - 1 - i)제곱 * (i번째 문자 - 64)의 정수로 변환한다.

  2. 1번 과정을 문자열의 모든 문자에 진행하며 변환된 각각의 정수 값을 누적 합산한다.

  3. 합산된 결과를 반환한다.

    Code

    class Solution {
     public int titleToNumber(String columnTitle) {
         int res = 0;
         for (int i = columnTitle.length() - 1; -1 < i; i--)
             res += Math.pow(26, columnTitle.length() - 1 - i) * (columnTitle.charAt(i) - 'A' + 1);
         return res;
     }
    }
    

    Time Complexity

    • 문자열의 길이를 n이라 가정할 때, 코드의 수행 시간을 좌우하는 것은 for반복문의 n번 계산 횟수이다. 따라서 본 솔루션은 O(n)의 시간 복잡도를 가진다.

Categories:

Updated:

Leave a comment