Question

  Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.

     American keyboard

題意

  輸入單字,若是能夠使用一列英文字母即可拼出,就要輸出這個單字

想法

  先把這三列字母設成三個 array,由第一個迴圈檢查每個輸入的單字,第二個迴圈檢查每個字母在哪個陣列中,若都在同個陣列即儲存此單字。

步驟

  1. 檢查字母

  2. 在同個陣列即儲存

程式碼

  /**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** findWords(char** words, int wordsSize, int* returnSize) {
    char first[10] = {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'};
    char second[9] = {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'};
    char third[7] = {'z', 'x', 'c', 'v', 'b', 'n', 'm'};
    int f=10, s=9, t=7;
    int is_f, is_s, is_t;
    int i, j, k;
    int total=0;
    char **rwords;
    rwords = malloc(wordsSize*sizeof(char*));
    for(i=0; i<wordsSize; i++)
    {
        is_f=0;
        is_s=0;
        is_t=0;
        for(j=0; j<strlen(words[i]); j++){
            for(k=0; k<f; k++){
                if(words[i][j] == first[k]){
                    is_f=1;
                    break;
                }
            }
            for(k=0; k<s; k++){
                if(words[i][j] == second[k]){
                    is_s=1;
                    break;
                }
            }
            for(k=0; k<t; k++){
                if(words[i][j] == third[k]){
                    is_t=1; 
                    break;
                }
            }
        }
        if((is_f==1 && is_s==0 && is_t==0) || (is_f==0 && is_s==1 && is_t==0) || (is_f==0 && is_s==0 && is_t==1)){
            rwords[total] = malloc((strlen(words[i]+1) * sizeof(char)));
            strcpy(rwords[total], words[i]);
            total++;
        }
    }
    *returnSize = total;
    return rwords;
}

arrow
arrow
    文章標籤
    LeetCode C
    全站熱搜

    Davis 發表在 痞客邦 留言(0) 人氣()