Below is my code. Is there better way to check for palindrome of string by inserting half of stack and also considering odd and even length ?
Another way (also overkill) is to make a frequency table of the characters. Now, at most one character can have an odd frequency. But that is only a necessary condition, not a sufficient one. So, look at the Collection class, there may be some useful methods available (for instance rotate, but there are some more).
Even though it's not the most efficient, I would prefer the clearest solution:
If the solution must be stack-based, I'd use the call stack:
Note that my second example only works for characters that fall within the Basic Multilingual Plane. My first example does work for all other Unicode characters, but does not take combining characters into account. For instance, it may or may not return true for the string "hèh".
Robert D. Smith wrote:Why not something as simple as reversing a copy of the string, and then check if they are equal? Seems much simpler than running through a loop, counting characters, and such.
Stephan van Hulst wrote:... I would prefer the clearest solution:
To make it even clearer:
To the point about removing spaces and punctuation, that would be correct if you're checking for imperfect palindromes. The examples given that don't remove spaces and such check for perfect palindromes.
raghu kalachar wrote:
Below is my code.
Compare your code with this cleaned up version:
This version may seem a little more clever but it is also less clear, in my opinion. It still works the same though.
Try it out here: https://repl.it/@jlacar/StackBasedPalindromeCheck
For strings containing ligatures or accents, you might have to convert them to either of two normalized Unicode forms, depending on whether you want to consider the reverse of "æ!æ" either "æ!æ" or "ea!ea".
This is not always obvious. For instance, while people usually consider the ligature 'æ' one character, they also usually consider the ligature 'ﬁ' a combination of the 'f' and 'i' characters.
Stephan van Hulst wrote:I know I've mentioned this before, but a friendly reminder that that code will only work for characters that fall within the Basic Multilingual Plane. In practice this probably isn't much of a problem...
Good reminder but as you said, probably isn't much of a problem. Haven't run into a situation in real life where I actually need to check for palindromes. Really more an academic exercise in algorithms.
They occur about every other week in the crossword puzzle. Spoonerisms are slightly less frequent. When I see phrases like, “both ways,” or, “up and down,” I can suspect the solution will be palindromic. Of course I only use the letters A...Z.
Junilu Lacar wrote:. . . Haven't run into a situation in real life where I actually need to check for palindromes. . . .