(17 18)/48(6_4) 编程

本文展示了几个编程问题的解决方案,包括计算字符串中特定字符出现的次数,变形的杨辉三角问题,优化后的斐波那契数列计算,以及使用递归实现的字符串通配符匹配。这些问题涵盖了基础算法和数据结构的应用。
摘要由CSDN通过智能技术生成

1、计算某字符出现次数

int main() {
	char buf[1042] = { 0 };
	gets(buf);
	char ch;
	scanf("%c", &ch);
	int len = strlen(buf);
	int count[128] = { 0 };
	for (int i = 0; i < len; ++i)
	{
		count[buf[i]]++;
	}
	int res = count[ch];
	if (ch >= 'a'&&ch <= 'z')  //不区分大小写时,查找为小写,则还需要加上大写相对应的数量
	{
		res += count[ch - 32];
	}
	else if (ch >= 'A'&&ch <= 'Z')  //查找为大写,则还需要加上小写相对应的数量
	{
		res += count[ch + 32];
	}
	printf("%d\n", res);
	return 0;
}

2、杨辉三角的变形

//内存不够
int FindIndex(int n)
{
	int m = 2 * n - 1;                  //第n行具有的元素个数
	vector<vector<int>> ivv(n, vector<int>(m, 0));
	ivv[0][0] = 1;
	for (int i = 1; i < n; ++i)
	{
		ivv[i][0] = ivv[i][2 * i] = 1;       //第一列和最后一列为1
		for (int j = 1; j < 2 * i; ++j)
		{
			if (j == 1)
				ivv[i][j] = ivv[i - 1][j - 1] + ivv[i - 1][j];
			else if (j == 2 * i - 1)
				ivv[i][j] = ivv[i - 1][j - 2] + ivv[i - 1][j - 1];
			else
				ivv[i][j] = ivv[i - 1][j - 2] + ivv[i - 1][j - 1] + ivv[i - 1][j];
		}
	}
	for (int k = 0; k < m; k++)
	{
		if (ivv[n - 1][k] % 2 == 0)
			return k + 1;
	}
	return -1;
}
//找规律
int FindIndex(int n)
{
	if (n <= 2)
		return -1;
	if (n % 2 == 1)
		return 2;
	if (n % 4 == 0)
		return 3;
	return 4;
}
int  FindIndex(int n)
{
	if (n <= 2)
		cout << -1 << endl;
	else if (n % 4 == 1 || n % 4 == 3)
		cout << 2 << endl;
	else if (n % 4 == 2)
		cout << 4 << endl;
	else
		cout << 3 << endl;
	return 0;
}
int  FindIndex(int n)
{
	int Index[] = { 4, 2, 3, 2 };
	int res = -1;
	if (n > 2)
		res = Index[(n - 2) % 4];
	cout << res << endl;
	return 0;
}

3、统计每个兔子的总次数(Fibonacci数列)

//递归
int Fibonacci(int n)
{
	if (n <= 2)
		return 1;
	return Fibonacci(n - 1) + Fibonacci(n - 2);
}

//迭代
int Fibonacci(int n)
{
	int f1 = 1, f2 = 1, f = 2;
	if (n <= 2)
		return 1;
	int m = n - 2;
	while (m--)
	{
		f = f1 + f2;
		f1 = f2;
		f2 = f;
	}
	return f;
}

int main()
{
	int n;
	while (cin >> n)
	{
		int res = Fibonacci(n);
		cout << res << endl;
	}
	return 0;
}

4、字符串通配

//递归
bool StrMach(const char *p, const char *s)
{
	if (*p == '\0'&&*s == '\0')
		return true;
	if (*p == '\0' || *s == '\0')
		return false;
	if (*p == '?')
		return StrMach(p + 1, s + 1);
	else if (*p == '*')
		return StrMach(p + 1, s) || StrMach(p + 1, s + 1) || StrMach(p, s + 1);
	else if (*p == *s)
		return StrMach(p + 1, s + 1);
	else
		return false;
}

int main()
{
	string pattern, str;
	while (cin >> pattern >> str)
	{
		bool res = StrMach(pattern.c_str(), str.c_str());
		if (res)
			cout << "true" << endl;
		else
			cout << "false" << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值