Open carloscn opened 1 year ago
static bool is_prefix(const char *a, const char *b)
{
size_t len_a = strlen(a);
size_t len_b = strlen(b);
if (len_a > len_b) {
return false;
}
return 0 == strncmp(a, b, len_a);
}
static int32_t count_prefixes(const char *words[], size_t words_size, const char *s)
{
int32_t ret = 0;
size_t p_len;
UTILS_CHECK_PTR(words);
UTILS_CHECK_PTR(s);
UTILS_CHECK_LEN(words_size);
UTILS_CHECK_LEN(p_len = strlen(s));
for (size_t i = 0; i < words_size; i ++) {
const char *d_str = words[i];
UTILS_CHECK_PTR(d_str);
if (is_prefix(d_str, s)) {
ret ++;
}
}
finish:
return ret;
}
Description
You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.
Return the number of strings in words that are a prefix of s.
A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.
Example 1:
Input: words = ["a","b","c","ab","bc","abc"], s = "abc" Output: 3 Explanation: The strings in words which are a prefix of s = "abc" are: "a", "ab", and "abc". Thus the number of strings in words which are a prefix of s is 3.
Example 2:
Input: words = ["a","a"], s = "aa" Output: 2 Explanation: Both of the strings are a prefix of s. Note that the same string can occur multiple times in words, and it should be counted each time.
Constraints:
1 <= words.length <= 1000 1 <= words[i].length, s.length <= 10 words[i] and s consist of lowercase English letters only.