Pretty straightforward problem. But I made one small mistake when checking for mirrored strings
.
Let’s say you have a string $s$. When you check for $s$ to be a palindrome, you start iterating from index $0$ and iterate just before index $\floor{\ddfrac{s.length}{2}}$. We can express it in terms of range as $\bigg[0,\floor{\ddfrac{s.length}{2}}\bigg)$.
If length of $s$ is even, all the characters are compared. For example, if $s = \textrm{ABBA}$, then $(A,A)$ and $(B,B)$ pairs are checked. But if the length is odd, then the middle character, namely the character at index $\ddfrac{s.length + 1}{2}$ is left alone, otherwise we would be checking it with itself which would obviously return true. For example, if $s = \textrm{ABA}$, then only $(A,A)$ pair is checked. $B$ is not compared with itself.
But that’s not the case when you’re dealing with mirrored palindromes. In case the length is even, it’s business as usual. But if the length is odd, then you would also have to check if the middle character is reverse of itself or not. I forgot to check it!
Let’s see the difference in code.
Here’s the isRegularPalindrome
function:
and here’s the isMirroredString
function:
See the difference in the for
loop termination? Essentially in case of mirrored strings, we’re checking up to $\floor{\ddfrac{s.length}{2}}$, namely the middle character is also checked for reverse.
We can also express it in terms of range,
\begin{aligned} \bigg[0,\floor{\ddfrac{s.length}{2}}\bigg) & \longleftarrow \textrm{Regular Palindrome} \newline \bigg[0,\floor{\ddfrac{s.length}{2}}\bigg ] & \longleftarrow \textrm{Mirrored String} \end{aligned}
Here’s the final implementation in C++
:
Sharing is caring. Share this story in...
Share: Twitter Facebook LinkedIn