0ms C++ Solution


  • 11

    The following is the C++ implementation of the suggested solution using a look-up table (implemented as an unordered_map). It takes 0 ms. But, I wonder, are there any real applications of strobogrammatic numbers?

    class Solution {
    public:
        bool isStrobogrammatic(string num) {
            unordered_map<char, char> lut{{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}};
            int n = num.length();
            for (int l = 0, r = n - 1; l <= r; l++, r--)
                if (lut.find(num[l]) == lut.end() || lut[num[l]] != num[r])
                    return false; 
            return true; 
        }
    };

  • 1

    You can also create the table like this:

    unordered_map<char, char> lut {{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}}; 
    

    Btw, I just came across this article about C++ features. Looks nice. I only skimmed it now, looking forward to read it later.

    As for "real applications", I'm guessing numerologists can use it :-)


  • 0

    Hi, Stefan. Thank you for suggesting the nice initialization feature and the article :-)


  • 0
    T

    You may make it little bit shorter on here
    if(lut.find(num[i])==lut.end() || lut[num[i]]!=num[j])


  • 0

    Hi, tamugaoqi. Thanks! The code is shorter now :-)


  • 0
    P

    C++ allocator for char default value is '\0', which is different from '0' to '9'. so you can remove this check lut.find(num[l]) == lut.end()
    Code likes below:

    class Solution {
    public:
        bool isStrobogrammatic(string num) {
            unordered_map<char, char> m{{'0','0'}, {'1','1'}, {'6','9'}, {'8','8'}, {'9','6'}};
            int left = 0, right = num.length() - 1;
            while (left <= right) {
                if (m[num[left++]] != num[right--]) return false;
            }
            return true;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.