问题
An orderly trail of ants is marching across the park picnic area.
It looks something like this:
..ant..ant.ant…ant.ant..ant.ant….ant..ant.ant.ant…ant..
But suddenly there is a rumour that a dropped chicken sandwich has
been spotted on the ground ahead. The ants surge forward! Oh No, it’s
an ant stampede!! Some of the slower ants are trampled, and their
poor little ant bodies are broken up into scattered bits. The
resulting carnage looks like this:
…ant…ant..nat.ant.t..ant…ant..ant..ant.anant..t
Can you find how many ants have died? —— [ codewars ]
提醒:
” ant “代表正常蚂蚁,其他为非正常蚂蚁;
两个头一个身体或者一个身体两个头都只代表两只死掉的蚂蚁。
思考
想要知道多少只死去的蚂蚁,我们就需要弄清有多少散乱的“头”和“身体”。如果“头”的数目多余“身体”,则用“头”数目代表死去蚂蚁数目;反之,则用“身体”代表死去蚂蚁的数目。“ant”代表的一只蚂蚁,那各个字母有代表着蚂蚁的什么部位呢?其实,不管是 ‘a’,‘n’,‘t’中的哪一个,都是蚂蚁的一部分,我们只需要统计不正常蚂蚁的‘a’,‘n’,‘t’的个数即可,最多的就代表总共死去的蚂蚁数目。
代码
接下来用C语言代码来实现:
#include
#include
int deadAntCount(const char* ants)
{
int a_all = 0;
int n_all = 0;
int t_all = 0;
int a_alive = 0;
int n_alive = 0;
int t_alive = 0;
int a_died;
int n_died;
int t_died;
for (ants; *ants != '\0'; ants++)
{
if (*ants == 'a')a_all++;
if (*ants == 'n')n_all++;
if (*ants == 't')t_all++;
if (*ants == 'a'&&*(ants + 1) == 'n'&&*(ants + 2) == 't')
{
a_alive++;
n_alive++;
t_alive++;
}
}
a_died = a_all - a_alive;
n_died = n_all - n_alive;
t_died = t_all - t_alive;
return (int)fmax(a_died,fmax(n_died,t_died));
}
//测试主函数
int main()
{
int a1 = deadAntCount("ant ant ant ant");
int a2 = deadAntCount("");
int a3 = deadAntCount("ant anantt aantnt");
int a4 = deadAntCount("ant ant .... a nt");
printf("%d,%d,%d,%d", a1, a2, a3, a4);
return 0;
}
测试结果