leetcode

    xiaoxiao2025-04-24  9

    A message containing letters from A-Z is being encoded to numbers using the following mapping:

    ‘A’ -> 1 ‘B’ -> 2 … ‘Z’ -> 26 Given an encoded message containing digits, determine the total number of ways to decode it.

    For example, Given encoded message “12”, it could be decoded as “AB” (1 2) or “L” (12).

    The number of ways decoding “12” is 2.

    Subscribe to see which companies asked this question


    DP O(N)


    class Solution { public: int numDecodings(string s) { if (s.length() == 0) return 0; if (s.length() == 1) return s[0] != '0'; int dp[2], rec; dp[0] = 1; dp[1] = s[0] != '0'; for (int i = 2; i <= s.length(); ++i) { rec = 0; if (s[i - 1] != '0') rec += dp[(i - 1)&1]; if (s.substr(i - 2, 2) <= "26" && s[i - 2] != '0') rec += dp[i&1]; dp[i&1] = rec; } return dp[s.length()&1]; } };
    转载请注明原文地址: https://ju.6miu.com/read-1298387.html
    最新回复(0)