给你一个字符串数组 words
,找出并返回数组中的 第一个回文字符串 。如果不存在满足要求的字符串,返回一个 空字符串 ""
。
回文字符串 的定义为:如果一个字符串正着读和反着读一样,那么该字符串就是一个 回文字符串 。
示例 1:
输入:words = ["abc","car","ada","racecar","cool"] 输出:"ada" 解释:第一个回文字符串是 "ada" 。 注意,"racecar" 也是回文字符串,但它不是第一个。
示例 2:
输入:words = ["notapalindrome","racecar"] 输出:"racecar" 解释:第一个也是唯一一个回文字符串是 "racecar" 。
示例 3:
输入:words = ["def","ghi"] 输出:"" 解释:不存在回文字符串,所以返回一个空字符串。
提示:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
仅由小写英文字母组成
class Solution:
def firstPalindrome(self, words: List[str]) -> str:
def check(s):
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
for word in words:
if check(word):
return word
return ''
class Solution {
public String firstPalindrome(String[] words) {
for (String word : words) {
if (check(word)) {
return word;
}
}
return "";
}
private boolean check(String s) {
for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}
class Solution {
public:
string firstPalindrome(vector<string>& words) {
for (auto& word : words)
if (check(word)) return word;
return "";
}
bool check(string s) {
for (int i = 0, j = s.size() - 1; i < j; ++i, --j)
if (s[i] != s[j]) return false;
return true;
}
};
func firstPalindrome(words []string) string {
check := func(s string) bool {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
if s[i] != s[j] {
return false
}
}
return true
}
for _, word := range words {
if check(word) {
return word
}
}
return ""
}
function firstPalindrome(words: string[]): string {
for (const word of words) {
let left = 0;
let right = word.length - 1;
while (left < right) {
if (word[left] !== word[right]) {
break;
}
left++;
right--;
}
if (left >= right) {
return word;
}
}
return '';
}
impl Solution {
pub fn first_palindrome(words: Vec<String>) -> String {
for word in words.iter() {
let s = word.as_bytes();
let mut left = 0;
let mut right = s.len() - 1;
while (left < right) {
if (s[left] != s[right]) {
break;
}
left += 1;
right -= 1;
}
if left >= right {
return word.clone();
}
}
String::new()
}
}
char *firstPalindrome(char **words, int wordsSize) {
for (int i = 0; i < wordsSize; i++) {
int left = 0;
int right = strlen(words[i]) - 1;
while (left < right) {
if (words[i][left] != words[i][right]) {
break;
}
left++;
right--;
}
if (left >= right) {
return words[i];
}
}
return "";
}