Find First Palindromic String in the Array

In this problem, we need to find the first string in the given list that is a palindrome. A palindrome is a word that reads the same backward as forward. We can check if a string is a palindrome by comparing it to its reversed version. If they are the same, the string is a palindrome.

Python solution:

1
2
3
4
5
6
7
8
9
class Solution:
    def firstPalindrome(self, words: List[str]) -> str:
        # Traverse through the list of words
        for word in words:
            # Check if the word is the same as its reverse
            if word == word[::-1]:
                return word
        # If no palindromic string is found, return an empty string
        return ""

This function iterates through the list of words, checks if each word is a palindrome, and if it is, returns that word immediately. If the function goes through all the words without finding a palindrome, it returns an empty string.