
Problem
Solution
Submissions
Check if a string is a palindrome
Certification: Basic Level
Accuracy: 80%
Submissions: 5
Points: 5
Write a C# program to implement the IsPalindrome(string s) function, which determines if a string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, ignoring case, spaces, and non-alphanumeric characters.
Algorithm
- Step 1: Remove all non-alphanumeric characters from the string.
- Step 2: Convert the string to lowercase.
- Step 3: Check if the resulting string reads the same forward and backward.
- Step 4: Return true if the string is a palindrome, false otherwise.
Example 1
- Input: s = "A man, a plan, a canal: Panama"
- Output: true
- Explanation:
- After removing non-alphanumeric characters and converting to lowercase: "amanaplanacanalpanama".
- Reading this forward and backward is the same, so it's a palindrome.
Example 2
- Input: s = "race a car"
- Output: false
- Explanation:
- After removing non-alphanumeric characters and converting to lowercase: "raceacar".
- Reading this forward: "raceacar"
- Reading this backward: "racaecar"
- These are different, so it's not a palindrome.
Constraints
- 1 ≤ s.length ≤ 2 * 10^5
- s consists of printable ASCII characters
- Time Complexity: O(n)
- Space Complexity: O(1) if done in-place with two pointers, or O(n) if creating a new string
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use two pointers, one starting from the beginning and one from the end, moving toward the center
- Skip non-alphanumeric characters and ignore case during comparison
- Alternatively, create a filtered string first, then check if it equals its reverse
- Be careful with edge cases such as empty strings or strings with only non-alphanumeric characters