LeetCode (D)

Decode Ways
 
AC Rate: 471/2906
My Submissions

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
 
AC Rate: 537/3649
My Submissions

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;
	}
};



Distinct Subsequences
 
AC Rate: 452/2049
My Submissions

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];
	}
};










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值