[LeetCode] 2108. Find First Palindromic String in the Array

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.

Example 1:
Input: words = ["abc","car","ada","racecar","cool"]
Output: "ada"
Explanation: The first string that is palindromic is "ada".
Note that "racecar" is also palindromic, but it is not the first.

Example 2:
Input: words = ["notapalindrome","racecar"]
Output: "racecar"
Explanation: The first and only string that is palindromic is "racecar".

Example 3:
Input: words = ["def","ghi"]
Output: ""
Explanation: There are no palindromic strings, so the empty string is returned.

Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] consists only of lowercase English letters.

找出数组中的第一个回文字符串。

给你一个字符串数组 words ,找出并返回数组中的 第一个回文字符串 。如果不存在满足要求的字符串,返回一个 空字符串 "" 。
回文字符串 的定义为:如果一个字符串正着读和反着读一样,那么该字符串就是一个 回文字符串 。

思路

找到 input 数组里第一个出现的回文串。

复杂度

时间O(mn) - m个单词,单词平均长度为n
空间O(1)

代码

Java实现

class Solution {
public String firstPalindrome(String[] words) {
for (String w : words) {
if (helper(w)) {
return w;
}
}
return "";
}
public boolean helper(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;
}
}

相关题目

7. Reverse Integer
9. Palindrome Number
2108. Find First Palindromic String in the Array
posted @   CNoodle  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2021-02-13 [LeetCode] 719. Find K-th Smallest Pair Distance
2020-02-13 [LeetCode] 134. Gas Station
2020-02-13 [LeetCode] 70. Climbing Stairs
2020-02-13 [LeetCode] 71. Simplify Path
点击右上角即可分享
微信分享提示