LeetCode168——Excel表列名称

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/86475807

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/excel-sheet-column-title/description/

题目描述:

知识点:哈希表、进制转换

思路:进制转换

首先为数字和字符的转换建立一个哈希表。

通过观察,我们发现可以把列名称当作一个26进制数,该26进制数单位数的范围是A ~ Z,分别对应0 ~ 25。而对于本题题给的映射,A ~ Z对应的是1 ~ 26,因此每轮循环开始的时候都需要n--操作。

时间复杂度是O(n),n为输入的正整数。空间复杂度是O(1)。

JAVA代码:

class Solution {
    public String convertToTitle(int n) {
        HashMap<Integer, Character> hashMap = new HashMap<>();
        for(int i = 0; i < 26; i++){
            hashMap.put(i, (char)('A' + i));
        }
        StringBuilder stringBuilder = new StringBuilder();
        while(n-- >= 0){
            stringBuilder.append(hashMap.get(n % 26));
            n /= 26;
            if(0 == n){
                break;
            }
        }
        return stringBuilder.reverse().toString();
    }
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/86475807
今日推荐