Implement the validPalindromeAlphanumeric method that checks whether a text is a palindrome after ignoring non-alphanumeric characters.

The input contains a string text. Your task is to check whether it is a valid palindrome after ignoring spaces, punctuation, and letter case.

Only alphanumeric characters should be compared. For example, A man a plan a canal Panama becomes a palindrome after ignoring spaces and case, so the answer is true.

Example 1

Input
text (string) = A man a plan a canal Panama
Returns (boolean) true

Example 2

Input
text (string) = race a car
Returns (boolean) false

Example 3

Input
text (string) = 0P
Returns (boolean) false

Use two pointers, one starting at the beginning of the string and one starting at the end.

Move the left pointer forward until it points to an alphanumeric character. Move the right pointer backward in the same way. Then compare both characters in lowercase form.

If any pair does not match, return false. If the pointers meet or cross after all comparisons, the string is a valid palindrome.

Pseudocode:

function validPalindromeAlphanumeric(text):
    left = 0
    right = length(text) - 1
    while left < right:
        while left < right and text[left] is not alphanumeric:
            left++
        while left < right and text[right] is not alphanumeric:
            right--
        if lowercase(text[left]) != lowercase(text[right]):
            return false
        left++
        right--
    return true
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.