Why it works
- A palindrome means the first character equals the last, the second equals the one before last, and so on. So compare from both ends.
- Punctuation and spaces take no part in the comparison: a pointer simply steps over them.
- The first pair that differs means "no". Once the pointers meet, every pair has matched: "yes".
Complexity
Time O(n): each pointer crosses the string at most once. Memory O(1): no cleaned-up copy of the string is made.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗