carloscn / structstudy

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

leetcode500:键盘行(keyboard-row) #110

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。

美式键盘 中:

第一行由字符 "qwertyuiop" 组成。 第二行由字符 "asdfghjkl" 组成。 第三行由字符 "zxcvbnm" 组成。

image

示例 1:

输入:words = ["Hello","Alaska","Dad","Peace"] 输出:["Alaska","Dad"] 示例 2:

输入:words = ["omk"] 输出:[] 示例 3:

输入:words = ["adsdf","sfd"] 输出:["adsdf","sfd"]  

提示:

1 <= words.length <= 20 1 <= words[i].length <= 100 words[i] 由英文字母(小写和大写字母)组成

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

carloscn commented 1 year ago

问题分析

static char *table[] = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};

static bool is_keyrow(const char *str)
{
    bool ret = false;
    size_t i = 0;
    size_t j = 0;
    size_t len = 0;
    char *result = NULL;
    char *target_table = NULL;

    len = strlen(str);
    for (i = 0; i < 3; i ++) {
        target_table = table[i];
        for (j = 0; j < len; j ++) {
            result = strchr(target_table, utils_conv_lowercase(str[j]));
            if (NULL == result) {
                break;
            }
        }
        if (j == len) {
            ret = true;
            goto finish;
        }
    }

finish:
    return ret;
}

static int32_t key_row(STRLIST_T *strlist_in, STRLIST_T *strlist_out)
{
    int32_t ret = 0;
    size_t i = 0;
    size_t j = 0;
    bool result = false;

    UTILS_CHECK_PTR(strlist_in);
    UTILS_CHECK_PTR(strlist_out);

    for (i = 0; i < strlist_get_size(strlist_in); i ++) {
        result = is_keyrow((const char*) strlist_get_str_at(strlist_in, i));
        if (true == result) {
            strlist_add(strlist_out, strlist_get_str_at(strlist_in, i));
        }
    }

finish:
    return ret;
}
carloscn commented 1 year ago

code:

https://github.com/carloscn/structstudy/blob/master/c_programming/str/31_keyboard-row_500.c

result:

image