[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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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