C++ 56ms well organized code.


  • 0
    J
    class Solution {
     public:
      int numDecodings(const std::string &s) {
        constexpr std::uint64_t base = 1000000007ull;
    
        // The first character.
        std::uint64_t v0 = 1;
        std::uint64_t v1 = nd(s[0]);
    
        // The main loop.
        for (std::size_t i = 1; i < s.length(); ++i) {
          std::uint64_t nv = v0 * nd(s[i-1], s[i]) + v1 * nd(s[i]);
          if (nv > base) { nv %= base; }
          v0 = v1;
          v1 = nv;
        }
    
        return v1;
      }
    
     private:
      inline int nd(const char c) const {
        switch (c) {
          case '0': return 0;
          case '*': return 9;
          default:  return 1;
        }
      }
    
      inline int nd(const char c0, const char c1) const {
        if (c1 == '*') {
          switch (c0) {
            case '1': return 9;
            case '2': return 6;
            case '*': return 15;
            default:  return 0;
          }
        } else {
          switch (c0) {
            case '1': return 1;
            case '2': return c1 <= '6';
            case '*': return (c1 <= '6') + 1;
            default:  return 0;
          }
        }
      }
    };
    

Log in to reply
 

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