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