Context free grammar for this language

1.1k views Asked by At

I'm working on some test preparation material and stuck on this problem.

Show a context free grammar for L = {w e {a,b}*: w = wR and every a is immediately followed by a b}.

wR is w in reverse. So, in english, a palindrome with every "a" being followed by a "b", using any number of a's and b's.

So far, I got this for the reverse portion, but I can't figure out how to incorporate the every a is followed by a b part while ensuring the palindrome property will still hold.

S -> bSb | b | [the empty string]

Any help is greatly appreciated!

1

There are 1 answers

1
buc On BEST ANSWER

Since every "a" must be followed by a "b", and the resulting word must be palindrome (it is the same if being read from the end to the beginning), this implies that every "a" must also be preceeded by a "b".

We start building the word from the middle, growing in both directions. The rule is that when the middle section ends (and therefore begins) with an "a" (this is the nonterminal A), then it must be followed (and preceeded) by a "b". On the other end, when the middle section is sorrounded by "b"s (this is nonterminal B), it can expand with a single "a" (the previous case), or any number of "b"s. The special case of evenly numbered "b"s in the middle are also handled. The start symbol S only allows words limited by "b"s, therefore all rules are matched.

S -> B | [empty]
B -> bAb | bBb | bb | b
A -> aBa | a

Edit: My previous solution was incorrect, I hope this works now.