A - AB Palindrome Editorial by evima
[1] Looking at the first and last characters
If the first character in \(S\) is A, it cannot be changed to B.
Similarly, if the last character in \(S\) is B, it cannot be changed to A.
Therefore, if the first and last characters in \(S\) are A and B, respectively, \(S\) cannot be turned into a palindrome.
Now, let us consider the case the first character is B or the last character is A.
If the first character in \(S\) is B, and \(N\) is at least \(3\):
By performing the operation for \(2\)-nd and \(3\)-rd characters, then for the \(3\)-rd and \(4\)-th characters, and so on, we can turn \(S\) into BAAA…AAAB, a palindrome.
If the last character in \(S\) is A, and \(N\) is at least \(3\):
By performing the operation for \((N-2)\)-nd and \((N-1)\)-st characters, then for the \((N-3)\)-rd and \((N-2)\)-nd characters, and so on, we can turn \(S\) into ABBB…BBBA, a palindrome.
Notice that the argument above depends on the assumption that \(N\) is at least \(3\). Beware the case \(N=2\): \(S\) cannot be turned into a palindrome (only) if \(S\) is BA. (AA and BB are already palindromes.)
[2] The solution
Eventually, the answer is No only if one of the following holds, and Yes otherwise:
- the first and last characters in \(S\) are
AandB, respectively; - \(S\) is
BA.
[3] Sample implementation
Python:
n = int(input())
s = input()
print("Yes" if (s[0] == "B" or s[-1] == "A") and s != "BA" else "No")
posted:
last update: