【算法】5956. 找出数组中的第一个回文字符串(多语言实现)

154 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第1天,点击查看活动详情


5956. 找出数组中的第一个回文字符串:

给你一个字符串数组 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] 仅由小写英文字母组成

分析

  • 面对这道算法题目,我陷入了沉思。
  • 感觉就是遍历数组,然后遍历字符,判断是否回文,没什么可以大优化的地方。
  • 头尾双指针,判断字符是否相等,指针逐渐向中间重合。

题解

java

class Solution {
    public String firstPalindrome(String[] words) {
        for (String word : words) {
			int l = 0;
			int r = word.length() - 1;
			while (l < r
					&& word.charAt(l) == word.charAt(r)) {
				l++;
				r--;
			}
			if (l >= r) {
				return word;
			}
		}
		return "";
    }
}

c

char * firstPalindrome(char ** words, int wordsSize){
    for (int i = 0; i < wordsSize; ++i) {
        char* word = words[i];
        int l = 0;
        int r = strlen(word) - 1;
        while (l < r
               && word[l] == word[r]) {
            l++;
            r--;
        }
        if (l >= r) {
            return word;
        }
    }
    return "";
}

c++

class Solution {
public:
    string firstPalindrome(vector<string>& words) {
        for (string& word: words) {
            int l = 0;
            int r = word.size() - 1;
            while (l < r
                   && word[l] == word[r]) {
                l++;
                r--;
            }
            if (l >= r) {
                return word;
            }
        }
        return "";
    }
};

python

class Solution:
    def firstPalindrome(self, words: List[str]) -> str:
        return next((word for word in words if word == word[::-1]), '')
        

go

func firstPalindrome(words []string) string {
    for _, word := range words {
		l := 0
		r := len(word) - 1
		for l < r && word[l] == word[r] {
			l++
			r--
		}
		if l >= r {
			return word
		}
	}
	return ""
}

rust

impl Solution {
    pub fn first_palindrome(words: Vec<String>) -> String {
        for word in words.iter() {
            let bs = word.as_bytes();
            let mut l = 0;
            let mut r = word.len() - 1;
            while l < r && bs[l] == bs[r] {
                l += 1;
                r -= 1;
            }
            if l >= r {
                return word.clone();
            }
        }
        "".to_string()
    }
}

原题传送门:https://leetcode-cn.com/problems/find-first-palindromic-string-in-the-array/


非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~