LeetCode 171 Excelテーブルの列番号(Javaで実装)

タイトル説明:

タイトル説明


方法1(マップ):

class Solution {
    
    
    public int titleToNumber(String s) {
    
    
        Map<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i = 0;i < 26;i++){
    
    
            map.put((char) ('A'+i),i+1);
        }
        int len = s.length();
        int result = map.get(s.charAt(len-1));
        if(len < 2){
    
    
            return map.get(s.charAt(0));
        }else{
    
    
            double j = 1.0;
            for(int i = len-2;i >=0;i--){
    
    
                result = result + map.get(s.charAt(i))*(int)Math.pow(26,j);
                j++;
            }
        }
        return result;
    }
}

結果:

結果


長さに関係なく:

class Solution {
    
    
    public int titleToNumber(String s) {
    
    
        Map<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i = 0;i < 26;i++){
    
    
            map.put((char) ('A'+i),i+1);
        }
        int len = s.length();
        int result = 0;
       
            double j = 0.0;
            for(int i = len-1;i >=0;i--){
    
    
                result = result + map.get(s.charAt(i))*(int)Math.pow(26,j);
                j++;
            }
        return result;
    }
}

簡略化されたバージョン:(2ms高速)

class Solution {
    
    
    public int titleToNumber(String s) {
    
    
       double j = 0.0;
       int result = 0;
       int len = s.length();
       for(int i = len-1;i >=0;i--){
    
    
            result = result + (s.charAt(i) - 'A' + 1)*(int)Math.pow(26,j);
            j++;
        }
        return result;
    }
}

結果:
結果

おすすめ

転載: blog.csdn.net/weixin_43752257/article/details/110943597