Leetcode 2108: Find First Palindromic String in the Array

Pierre-Marie Poitevin
1 min readJan 13, 2022

In this problem, we want to find the first String that is a palindrome in an array of Strings.

Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "".

A string is palindromic if it reads the same forward and backward.

No particular difficulty on the algorithm side here, we go through the array, and when we find a string that is a palindrome, we return it. At the end, if we didn’t find such string, we return the empty string.

To test if a string is a palindrome, simply check each character of the string with its “mirror” character. That is for index i the mirror index is n — 1 — i. All the mirror characters should match. If it doesn’t match just return false.

This is the code I obtained in Java:

class Solution {

boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < n/2; i++) {
if (s.charAt(i) != s.charAt(n-1-i)) {
return false;
}
}
return true;
}

public String firstPalindrome(String[] words) {
for (String word : words) {
if (isPalindrome(word)) {
return word;
}
}
return "";
}
}

Happy coding :)

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet