carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2108: Find First Palindromic String in the Array #340

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

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

carloscn commented 1 year ago

Analysis

int32_t first_palindrome(const char **words, size_t words_size, char *out_str)
{
    int32_t ret = 0;
    char const *str_e = NULL;

    UTILS_CHECK_PTR(words);
    UTILS_CHECK_PTR(out_str);
    UTILS_CHECK_LEN(words_size);

    out_str[0] = '\0';

    size_t str_len = 0;
    for (size_t i = 0; i < words_size; i ++) {
        str_e = words[i];
        UTILS_CHECK_PTR(str_e);

        str_len = strlen(str_e);
        if (str_len = 0) {
            continue;
        }

        size_t j = 0, k = str_len - 1;
        while (j != k) {
            if (str_e[j ++] != str_e[k --]) {
                break;
            }
        }

        if (i == k) {
            strcpy(out_str, str_e);
            break;
        }
    }

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168811 https://github.com/carloscn/structstudy/commit/87df75f5cd01fe90a54668959eaa5c834fea006b