给你一个字符串数组 words
,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。
美式键盘 中:
- 第一行由字符
"qwertyuiop"
组成。 - 第二行由字符
"asdfghjkl"
组成。 - 第三行由字符
"zxcvbnm"
组成。 -
示例 1:
输入:words = ["Hello","Alaska","Dad","Peace"] 输出:["Alaska","Dad"]
示例 2:
输入:words = ["omk"] 输出:[]
示例 3:
输入:words = ["adsdf","sfd"] 输出:["adsdf","sfd"]
-
#include <stdio.h> #include <stdlib.h> #include <string.h> char** findWords(char** words, int wordsSize, int* returnSize) { char *ptr[] = {"qwertyuiop","asdfghjkl","zxcvbnm"}; int pos1 = 0; int pos2 = 0; int count = 0; int start = 0; char **str = malloc(sizeof(char)*wordsSize); for(int i = 0;i < wordsSize;i++)//words行数 { pos1 = 0; pos2 = 0; for(int j = 0;j < 3;j++)//ptr行数 { while(words[i][pos1] != '\0' && ptr[j][pos2] != '\0')//将words的第一行第一个元素遍历ptr第一个每一个元素 { if(words[i][pos1] != ptr[j][pos2] && words[i][pos1] != ptr[j][pos2] - 32 )//不相等,ptr移向下一个元素 { pos2++; } else if(words[i][pos1] == ptr[j][pos2] || words[i][pos1] == ptr[j][pos2] - 32)//相等,words移向下一个元素,ptr从第一个元素重新开始,计数+1 { pos1++; pos2 = 0; count++; } } if(count > 0 && count < strlen(words[i])-1)//一轮过后,如果计数存在并且,小于words的长度,说明words第一行元素不在同一行 { count = 0; break; } if(count == strlen(words[i]))// { str[start++] = words[i]; count = 0; break; } pos1 = 0; pos2 = 0; } } *returnSize = start; return str; } int main() { char *words[] = {"Asd","zXc"}; int wordsSize = sizeof(words)/sizeof(words[0]); int returnSize = 0; char ** p = findWords(words,wordsSize,&returnSize); for(int i = 0;i < returnSize;i++) { printf("%s ",p[i]); } printf("\n"); free(p); p = NULL; return 0; }