carloscn / structstudy

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

leetcode520:检测大写字母(detect-capital) #113

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

我们定义,在以下情况时,单词的大写用法是正确的:

全部字母都是大写,比如 "USA" 。 单词中所有字母都不是大写,比如 "leetcode" 。 如果单词不只含有一个字母,只有首字母大写, 比如 "Google" 。 给你一个字符串 word 。如果大写用法正确,返回 true ;否则,返回 false 。

示例 1: 输入:word = "USA" 输出:true

示例 2: 输入:word = "FlaG" 输出:false  

提示: 1 <= word.length <= 100 word 由小写和大写英文字母组成

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/detect-capital

carloscn commented 1 year ago

问题分析

采用计数方式,然后对数字进行判断。

static int32_t detect_capital(const char* str, bool *result)
{
    int32_t ret = 0;
    size_t len = 0;
    size_t i = 0;
    size_t c_count = 0;
    size_t l_count = 0;

    UTILS_CHECK_PTR(str);
    UTILS_CHECK_PTR(result);
    UTILS_CHECK_LEN(len = strlen(str));

    for (i = 0; i < len; i ++) {
        if (utils_is_capital(str[i])) {
            c_count ++;
        } else if (utils_is_lowercase(str[i])) {
            l_count ++;
        }
    }

    if (c_count == len && l_count == 0) {
        *result = true;
        goto finish;
    }

    if (c_count == 0 && l_count == len) {
        *result = true;
        goto finish;
    }

    if (c_count == 1 &&
        l_count == len - 1 &&
        utils_is_capital(str[0])) {
        *result = true;
        goto finish;
    }

    *result = false;

finish:
    return ret;
}
carloscn commented 1 year ago

code

https://github.com/carloscn/structstudy/blob/master/c_programming/str/33_detect-capital_520.c https://github.com/carloscn/structstudy/blob/master/rust_programming/array/src/n33_detect_capital_520.rs

result

image