Just for fun, I wrote the SQL version (SQL Server 2012):
if object_id('dbo.MaxNgram','IF') is not null drop function dbo.MaxNgram; go create function dbo.MaxNgram( @text varchar(max) ,@length int ) returns table with schemabinding as return with Delimiter(c) as ( select ' '), E1(N) as ( select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1) )T(N) ), E2(N) as ( select 1 from E1 a cross join E1 b ), E6(N) as ( select 1 from E2 a cross join E2 b cross join E2 c ), tally(N) as ( select top(isnull(datalength(@text),0)) ROW_NUMBER() over (order by (select NULL)) from E6 ), cteStart(N1) as ( select 1 union all select t.N+1 from tally t cross join delimiter where substring(@text,tN,1) = delimiter.c ), cteLen(N1,L1) as ( select s.N1, isnull(nullif(charindex(delimiter.c,@text,s.N1),0) - s.N1,8000) from cteStart s cross join delimiter ), cteWords as ( select ItemNumber = row_number() over (order by l.N1), Item = substring(@text, l.N1, l.L1) from cteLen l ), mask(N) as ( select top(@length) row_Number() over (order by (select NULL)) from E6 ), topItem as ( select top 1 substring(Item,mN,@length) as Ngram ,count(*) as Length from cteWords w cross join mask m where mN <= datalength(w.Item) + 1 - @length and @length <= datalength(w.Item) group by substring(Item,mN,@length) order by 2 desc, 1 ) select ds from ( select top 1 NGram,Length from topItem ) t cross apply (values (cast(NGram as varchar)),(cast(Length as varchar))) d(s) ; go
which when called with an input pattern is provided by OP
set nocount on; select s as [ ] from MaxNgram( 'aaaab a0a baaab c aab' ,3 ); go
gives at will