You are given a string ‘S’. Your task is to check whether the string is palindrome or not. For checking palindrome, consider alphabets and numbers only and ignore the symbols and whitespaces.

Note :

String 'S' is NOT case sensitive.

Example :

Let S = “c1 O$d@eeD o1c”. If we ignore the special characters, whitespaces and convert all uppercase letters to lowercase, we get S = “c1odeedo1c”, which is a palindrome. Hence, the given string is also a palindrome.
Input format :
The very first line of input contains an integer 'T' denoting the number of test cases. The first line of every test case contains the string 'S'.
Output format :
For each test case, print “Yes” if 'S' is a palindrome, and “No” otherwise. Print the output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Follow Up :
Can you solve the problem using O(1) space complexity?
Constraints :
1 <= T <= 100 1 <= Length(S) <= 10^4 Where 'T' denotes the number of test cases and 'S' denotes the given string. Time Limit : 1 sec

Implementation in Python

def is_palindrome(S):
    # Function to check if a string is a palindrome
    
    # Convert the string to lowercase
    S = S.lower()
    
    # Initialize a new string to store only alphanumeric characters
    alphanumeric = ''
    
    # Iterate through the characters of the string
    for char in S:
        # Check if the character is alphanumeric
        if char.isalnum():
            # If alphanumeric, add it to the new string
            alphanumeric += char
    
    # Check if the new string is equal to its reverse
    return alphanumeric == alphanumeric[::-1]

# Main function
if __name__ == "__main__":
    # Read the number of test cases
    T = int(input().strip())

    # Iterate through each test case
    for _ in range(T):
        # Read the string for the current test case
        S = input().strip()
        
        # Check if the string is a palindrome and print the result
        if is_palindrome(S):
            print("Yes")
        else:
            print("No")

By

Leave a Reply

Discover more from Geeky Codes

Subscribe now to keep reading and get access to the full archive.

Continue reading