描述:
一群蚂蚁井然有序地行进在公园野餐区,像这样:
..ant..ant.ant…ant.ant..ant.ant….ant..ant.ant.ant…ant..
突然,有蚁传来消息说,前面有一个三明治掉在了地上。蚂蚁群闻讯后飞速前进,立刻就发生了蚂蚁踩踏事件。一些跑得慢的蚂蚁被踩的身首异处,尸骨无存,像这样:
…ant…ant..nat.ant.t..ant…ant..ant..ant.anant..t
你能找出被踩死的蚂蚁有几只吗?
例如:
DeadAntCount(“ant ant ant ant”) =>0
DeadAntCount(“…ant…ant..nat.ant.t..ant…ant..ant..ant.anant..t”) =>3
DeadAntCount(null) =>0
Mycode:
using System;
using System.Linq;
public class Kata
{
public static int DeadAntCount(string ants)
{
if(ants == null) return 0;
int originalAnt,aliveAnt,deadAnt;
int head = ants.Count(x => x == 'a');
int body = ants.Count(y => y == 'n');
int foot = ants.Count(z => z == 't');
originalAnt = Math.Max(head,Math.Max(body,foot));
aliveAnt = ants.Replace("ant","*").Count(o => o == '*');
deadAnt = originalAnt - aliveAnt;
return deadAnt;
}
}
CodeWar:
using System;
using System.Linq;
public class Kata
{
public static int DeadAntCount(string ants)
{
ants = ants?.Replace("ant", "") ?? "";
return Math.Max(ants.Count(c => c == 'a'), Math.Max(ants.Count(c => c == 'n'),ants.Count(c => c == 't')));
}
}