Leetcode 2108. Find First Palindromic String in the Array
You are given an array of strings words
. Your task is to find the first palindromic string in the array. A string is called a palindrome if it reads the same forward and backward. If there is no such string, return an empty string ""
.
""
.Here’s a possible implementation in Java to achieve the solution:
public class Solution {
public String firstPalindrome(String[] words) {
for (String word : words) {
if (isPalindrome(word)) {
return word;
}
}
return "";
}
private boolean isPalindrome(String word) {
int left = 0;
int right = word.length() - 1;
while (left < right) {
if (word.charAt(left) != word.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
// Driver code to test the solution
public static void main(String[] args) {
Solution solution = new Solution();
String[] words = {"abc", "car", "ada", "racecar", "cool"};
System.out.println(solution.firstPalindrome(words)); // Output: "ada"
}
}
Therefore, the total time complexity is O(m * L), where L is the maximum length of any string in the array. This ensures that our solution is efficient even for relatively large arrays of strings.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?