|
| 1 | +/** |
| 2 | + * [2108] Find First Palindromic String in the Array |
| 3 | + * |
| 4 | + * Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "". |
| 5 | + * A string is palindromic if it reads the same forward and backward. |
| 6 | + * |
| 7 | + * Example 1: |
| 8 | + * |
| 9 | + * Input: words = ["abc","car","ada","racecar","cool"] |
| 10 | + * Output: "ada" |
| 11 | + * Explanation: The first string that is palindromic is "ada". |
| 12 | + * Note that "racecar" is also palindromic, but it is not the first. |
| 13 | + * |
| 14 | + * Example 2: |
| 15 | + * |
| 16 | + * Input: words = ["notapalindrome","racecar"] |
| 17 | + * Output: "racecar" |
| 18 | + * Explanation: The first and only string that is palindromic is "racecar". |
| 19 | + * |
| 20 | + * Example 3: |
| 21 | + * |
| 22 | + * Input: words = ["def","ghi"] |
| 23 | + * Output: "" |
| 24 | + * Explanation: There are no palindromic strings, so the empty string is returned. |
| 25 | + * |
| 26 | + * |
| 27 | + * Constraints: |
| 28 | + * |
| 29 | + * 1 <= words.length <= 100 |
| 30 | + * 1 <= words[i].length <= 100 |
| 31 | + * words[i] consists only of lowercase English letters. |
| 32 | + * |
| 33 | + */ |
| 34 | +pub struct Solution {} |
| 35 | + |
| 36 | +// problem: https://leetcode.com/problems/find-first-palindromic-string-in-the-array/ |
| 37 | +// discuss: https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/?currentPage=1&orderBy=most_votes&query= |
| 38 | + |
| 39 | +// submission codes start here |
| 40 | + |
| 41 | +impl Solution { |
| 42 | + pub fn first_palindrome(words: Vec<String>) -> String { |
| 43 | + words |
| 44 | + .into_iter() |
| 45 | + .find(|w| w.chars().eq(w.chars().rev())) |
| 46 | + .unwrap_or_else(String::default) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// submission codes end |
| 51 | + |
| 52 | +#[cfg(test)] |
| 53 | +mod tests { |
| 54 | + use super::*; |
| 55 | + |
| 56 | + #[test] |
| 57 | + fn test_2108_example_1() { |
| 58 | + let words = vec_string!["abc", "car", "ada", "racecar", "cool"]; |
| 59 | + |
| 60 | + let result = "ada".to_string(); |
| 61 | + |
| 62 | + assert_eq!(Solution::first_palindrome(words), result); |
| 63 | + } |
| 64 | + |
| 65 | + #[test] |
| 66 | + fn test_2108_example_2() { |
| 67 | + let words = vec_string!["notapalindrome", "racecar"]; |
| 68 | + |
| 69 | + let result = "racecar".to_string(); |
| 70 | + |
| 71 | + assert_eq!(Solution::first_palindrome(words), result); |
| 72 | + } |
| 73 | + |
| 74 | + #[test] |
| 75 | + fn test_2108_example_3() { |
| 76 | + let words = vec_string!["def", "ghi"]; |
| 77 | + |
| 78 | + let result = "".to_string(); |
| 79 | + |
| 80 | + assert_eq!(Solution::first_palindrome(words), result); |
| 81 | + } |
| 82 | +} |
0 commit comments