carloscn / structstudy

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

leetcode434:字符串中的单词数(number-of-segments-in-a-string) #97

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。

请注意,你可以假定字符串里不包括任何不可打印的字符。

示例:

输入: "Hello, my name is John" 输出: 5 解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/number-of-segments-in-a-string

carloscn commented 1 year ago

问题分析

static inline bool is_char(uint32_t val)
{
    if ((val >= 'a' && val <= 'z') ||
        (val >= 'A' && val <= 'Z')) {
        return true;
    }
    return false;
}

static int32_t number_of_word(char *str, size_t *out)
{
    int32_t ret = 0;
    size_t str_len = 0;
    size_t i = 0;
    size_t i_count = 0;
    size_t n_count = 0;

    UTILS_CHECK_PTR(str);
    UTILS_CHECK_PTR(out);
    UTILS_CHECK_LEN(str_len = strlen(str));

    for (i = 0; i < str_len; i ++) {
        if (is_char((uint32_t)str[i])) {
            i_count ++;
        } else {
            n_count = (i_count == 0) ?
                      (n_count):
                      (i_count = 0, n_count + 1);
        }
    }
    *out = (i_count != 0) ? (n_count + 1) : (n_count);

finish:
    return ret;
}
carloscn commented 1 year ago

code:

https://github.com/carloscn/structstudy/blob/master/c_programming/str/28_number-of-segments-in-a-string_434.c

result:

image