Day of the week that is K days later

Given a string S, returns the maximum number of letters a that can be inserted into S (including at the front and end of S) so that the resulting string doesn’t contain three consecutive letters a. If string S already contains the substring aaa, then your function should return -1.

Example 1:

Input: aabab

Output: 3

Explanation:

A string aabaabaa can be made

Example 2:

Input: dog

Output: 8

Explanation:

A string aadaaoaagaa can be made

Example 3:

Input: aa

Output: 0

Explanation:

No longer string can be made.

Example 4:

Input: baaaa

Output: -1

Explanation:

There is a substring aaa

Try it yourself

Implementation

1
1
from itertools import groupby
2
2
def maxInserts(s):
3
-
    # WRITE YOUR BRILLIANT CODE HERE
3
+
    ans, last = 0, '#'
4
+
    for c, g in groupby(s):
5
+
        L = len(list(g))
6
+
          if c == 'a':
7
+
              if L < 3:
8
+
                  ans += 2 - L
9
+
              else:
10
+
                  return -1
11
+
        else:
12
+
            ans += 2 * (L - (last == 'a'))
13
+
        last = c
14
+
    ans += 2 * (s[-1] != 'a')
15
+
    return ans
16
+
4
17
if __name__ == '__main__':
5
18
    print(maxInserts(input()))