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.
class Solution {
public:
int numDecodings(string s) {
const int len = s.length();
if (len == 0) return 0;
vector<int> dp(len + 1, 0);
if (s[0] == '0')
dp[0] = dp[1] = 0;
else
dp[0] = dp[1] = 1;
for (int i = 2; i <= len; ++i) {
if (s[i - 1] != '0') dp[i] += dp[i - 1];
const int tmp = (s[i - 2] - '0') * 10 + (s[i - 1] - '0');
if (tmp >= 10 && tmp <= 26)
dp[i] += dp[i - 2];
}
return dp[len];
}
};
Divide two integers without using multiplication, division and mod operator.
class Solution {
public:
int divide(int dividend, int divisor) {
int ans = 0, t = 0;
long long a = dividend, b = divisor;
a = a < 0 ? -a : a;
b = b < 0 ? -b : b;
while (a >= b) {
b = b << 1;
++t;
}
b = b >> 1;
--t;
while (t >= 0) {
if (a >= b) {
a -= b;
ans += (1 << t);
}
--t;
b = b >> 1;
}
return (dividend ^ divisor) < 0 ? -ans : ans;
}
};
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE"
is a subsequence of "ABCDE"
while "AEC"
is not).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
class Solution {
public:
int numDistinct(string S, string T) {
const int m = S.length(), n = T.length();
vector<vector<int> > dp(m + 1, vector<int>(n + 1, 0));
for (int i = 0; i <= m; ++i) dp[i][0] = 1;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
dp[i][j] = dp[i - 1][j];
if (S[i - 1] == T[j - 1])
dp[i][j] += dp[i - 1][j - 1];
}
}
return dp[m][n];
}
};