在庆祝祖国母亲70华诞之际,老师给小乐乐出了一个问题。大家都知道China的英文缩写是CHN,那么给你一个字符串s,你需要做的是统计s中子序列“CHN”的个数。
子序列的定义:存在任意下标a < b < c,那么“s[a]s[b]s[c]”就构成s的一个子序列。如“ABC”的子序列有“A”、“B”、“C”、“AB”、“AC”、“BC”、“ABC”。
输入只包含大写字母的字符串s。(1 ≤ length ≤ 8000)
输出一个整数,为字符串s中子序列“CHN”的数量。
解题思路:找到C,在C后面找到H,在H后面确定N的数量,所有n的总数和即为CHN的数量。
第一个程序
#include<stdio.h>
#include<string.h>
int main()
{
char ch[8001] = { 0 };
int i = 0;
int j = 0;
int m = 0;
int count = 0;
gets(ch);
//判断该位是否为c,是则判断第一个h后n得个数,第二个h后n得个数,将这些个数相加
for (i = 0; i < strlen(ch) - 2; i++)
{
if (ch[i] == 'C')
{
for (j = i+1; j < strlen(ch)-1 ; j++)
{
if (ch[j] == 'H')
{
for (m = j+1; m < strlen(ch) ; m++)
{
if (ch[m] == 'N')
count++;
}
}
}
}
}
printf("%d", count);
return 0;
}
缺点:无法处理较大的数据量。
改进后的程序
#include<stdio.h>
#include<string.h>
int main()
{
char ch[8001] = { 0 };
int i = 0;
gets(ch);
long long int sum_C = 0;
long long int sum_H = 0;
long long int sum_N = 0;
for (i = 0; i < strlen(ch); i++)
{
if (ch[i] == 'C')
sum_C++;
if (ch[i] == 'H')
sum_H += sum_C;
if (ch[i] == 'N')
sum_N += sum_H;
}
printf("%lld", sum_N);
return 0;
}
两者区别:第一版程序,是由CHN正向的规律。定C再定H最后定N。第二版,是由CHN反向的规律下,定N再定H最后定C。