Leetcode P0246"Strobogrammatic Number" 题解

2021/01/02 Leetcode

博文中会简要介绍Leetcode P0246题目分析及解题思路。

“Strobogrammatic Number”是一道比较简单的题目,主要思路是建立数字和其旋转180度以后的数字之间的映射(如果旋转后能够构成一个数字的话),然后以数字为单位遍历一遍当前的数即可。

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Write a function to determine if a number is strobogrammatic. The number is represented as a string.

Example 1:

Input: num = "69"
Output: true

以下是Java的题解代码实现。

class Solution {
    private Map<Character, Character> ch2CharMap = null;
    
    public Solution() {
        this.ch2CharMap = new HashMap<>();
         
        this.ch2CharMap.put('6', '9');
        this.ch2CharMap.put('9', '6');
        this.ch2CharMap.put('1', '1');
        this.ch2CharMap.put('0', '0');
        this.ch2CharMap.put('8', '8');
    }
    
    public boolean isStrobogrammatic(String num) {
        int L = num.length();
        for (int idx=0; idx<(L+1)/2; ++idx) {
            char ch = num.charAt(idx);
            if (this.ch2CharMap.containsKey(ch)) {
                char mapped = this.ch2CharMap.get(ch);
                if (mapped != num.charAt(L-1-idx))
                    return false;
            }
            else 
                return false;
        }
        
        return true;
    }
}

以下是C++的题解代码实现。

class Solution {
public:
    
    Solution() {
        ch2ch_['6'] = '9';
        ch2ch_['9'] = '6';
        ch2ch_['8'] = '8';
        ch2ch_['1'] = '1';
        ch2ch_['0'] = '0';
    }
    
    bool isStrobogrammatic(string num) {
        int L = num.length();
        for (int idx=0; idx<(L+1)/2; ++idx) {
            if (ch2ch_.count(num[idx])) {
                char mapped = num[L-1-idx];
                if (mapped != ch2ch_[num[idx]])
                    return false;
            }
            else
                return false;
        }
        
        return true;
    }
    
private:
    unordered_map<char, char> ch2ch_;
};

Search

    Table of Contents