Palindrome problem
Problem
The palindrome problem is another classic algorithm question.Given the sentence, write the code checking if the sentence is a palindrome. Any non-alphabet characters should be ignored.
Examples:
A car, a man, a maraca.
A dog, a plan, a canal: pagoda.
A dog! A panic in a pagoda!
A lad named E. Mandala
A man, a plan, a canal: Panama.
Answer
The algorithm should ignore all but the alphabet. The expected running time is O(N).
This algorithm is quite straightforward.
We can set two pointers: start, and end. start pointer begins with the 0th position and the end pointer starts with $N-1$th position.
Each time we compare the characters pointed by these two points. If they don't match, it is not a palindrome.
If they do, increment a start pointer by 1 and decrement an end pointer by 1 and perform the comparison.
Repeat this process until start >= end.
If you have questions, feel free to add them to the comments.
Here is the code
Examples:
A car, a man, a maraca.
A dog, a plan, a canal: pagoda.
A dog! A panic in a pagoda!
A lad named E. Mandala
A man, a plan, a canal: Panama.
Answer
The algorithm should ignore all but the alphabet. The expected running time is O(N).
This algorithm is quite straightforward.
We can set two pointers: start, and end. start pointer begins with the 0th position and the end pointer starts with $N-1$th position.
Each time we compare the characters pointed by these two points. If they don't match, it is not a palindrome.
If they do, increment a start pointer by 1 and decrement an end pointer by 1 and perform the comparison.
Repeat this process until start >= end.
If you have questions, feel free to add them to the comments.
end of the code
UPDATE(2019-07-31): Solved the problem again. Had a bug in the logic.
Practice statistics
7:15: to write up the code
2:10: to debug the code. (1 bug in the while loop)
UPDATE(2022-06-22): Solve the problem again.
06:42: for algorithm and pseudo code
07:08: coding
03:30: code review
Comments
Post a Comment