for(1..<>){ <>; $_=<>; s/^BB/AB/ || s/^BAA/ABA/ || s/^BAB+/$&=~y,AB,BA,r/e || s/^ABA*\KB*/$&=~y,B,A,r/e || s/^AA/AB/; s/A+/$&=~y,A,B,r/e; print; }