动态规划 解析数字字符串

 

#include<iostream>
#include<string>
#include<vector>
using namespace std;
class solution
{
private:
	int dp(string s)
	{
		int j = 0,i=1;
		int n = s.length();
		int *a = new int[n+1];
		a[i++] = 1;
		int sum = 0;
		for (j=0; j <n; j++)
		{
			sum = (s[j] - '0') * 10 + (s[j] - '0');
			if (i == 2)
			{
				if (sum == 10 || sum == 20)
					a[i++] = 1;
				else if (sum > 10 && sum <= 26 && sum != 20)
					a[i++] = 2;
				else if (!sum)
					a[i++] = 0;
			}
			else if ((s[j] - '0') && (s[j - 1] - '0') && sum > 10 && sum <= 26)
				a[i++] = a[i - 1] + a[i - 2];
			else if ((s[j] - '0') && (s[j - 1] - '0') && sum > 26)
				a[i++] = a[i - 1];
			else if (!(s[j] - '0') && !(s[j - 1] - '0'))
				a[i++] = 0;
			else if ((s[j] - '0') && !(s[j- 1] - '0'))
				a[i++] = a[i - 1];
		}
		return a[i-1];
	}
public:
	void test(string s)
	{
		cout << dp(s);
	}
};
int main()
{
	string s = "12124";
	class solution a;
	a.test(s);
	system("pause");
	return 0;
}
发布了98 篇原创文章 · 获赞 1 · 访问量 4488

猜你喜欢

转载自blog.csdn.net/weixin_40823740/article/details/103354693