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

CNoodle / 2024-02-13 / 原文

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