以下为原创,如有错误,还望指出
贴原题:
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 theimage below.
American keyboardExample 1:
Input: [“Hello”, “Alaska”, “Dad”, “Peace”]
Output: [“Alaska”, “Dad”]Note: You may use one character in the keyboard more than once. You may assume the input string will only contain letters of alphabet.
解析:
本题是要判断单词是否在键盘同一行,如果是则返回。
那么我们只需要逐个判断一个单词占键盘的几行就可以了。我用三个变量分别代表该单词的某字母在哪一行,如果该单词的两个字母在不同行则直接进行判断下一个单词;否则,存入指针数组。(重新写了注释,应该还算清晰)
感觉这道题和leetcode 412. Fizz Buzz挺像,我在那道题里写了我对指针数组和数组指针的理解,以及返回值类型为char* 和char** 的区别,贴出我的解题链接:
http://blog.csdn.net/m0_37454852/article/details/78044895
C代码:
/**
* 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) {
*returnSize=0;
char** rewords=(char **)malloc(wordsSize*sizeof(char *));//待返回指针数组
char buff[50];//用于存放每个单词
for(int i=0, k=0; i<wordsSize; i++)
{
int r=strlen((*(words+i)));//该单词长度
int x=0, y=0, z=0;//代表是否占据某一行
for(int j=0; j<r; j++)
{
if(!x && (*(*(words+i)+j)=='Z' || *(*(words+i)+j)=='X' || *(*(words+i)+j)=='C' || *(*(words+i)+j)=='V'
|| *(*(words+i)+j)=='B' || *(*(words+i)+j)=='N' || *(*(words+i)+j)=='M'
|| *(*(words+i)+j)=='z' || *(*(words+i)+j)=='x' || *(*(words+i)+j)=='c' || *(*(words+i)+j)=='v'
|| *(*(words+i)+j)=='b' || *(*(words+i)+j)=='n' || *(*(words+i)+j)=='m'))
{
x=1;//最底层
}
else if(!y && (*(*(words+i)+j)=='A' || *(*(words+i)+j)=='S' || *(*(words+i)+j)=='D' || *(*(words+i)+j)=='F'
|| *(*(words+i)+j)=='G' || *(*(words+i)+j)=='H' || *(*(words+i)+j)=='J' || *(*(words+i)+j)=='K' || *(*(words+i)+j)=='L'
|| *(*(words+i)+j)=='a' || *(*(words+i)+j)=='s' || *(*(words+i)+j)=='d' || *(*(words+i)+j)=='f'
|| *(*(words+i)+j)=='g' || *(*(words+i)+j)=='h' || *(*(words+i)+j)=='j' || *(*(words+i)+j)=='k' || *(*(words+i)+j)=='l'))
{
y=1;//中间层
}
else if(!z && (*(*(words+i)+j)=='Q' || *(*(words+i)+j)=='W' || *(*(words+i)+j)=='E' || *(*(words+i)+j)=='R'
|| *(*(words+i)+j)=='T' || *(*(words+i)+j)=='Y' || *(*(words+i)+j)=='U' || *(*(words+i)+j)=='I' || *(*(words+i)+j)=='O'
|| *(*(words+i)+j)=='P'
|| *(*(words+i)+j)=='q' || *(*(words+i)+j)=='w' || *(*(words+i)+j)=='e' || *(*(words+i)+j)=='o' || *(*(words+i)+j)=='p'
|| *(*(words+i)+j)=='r' || *(*(words+i)+j)=='t' || *(*(words+i)+j)=='y' || *(*(words+i)+j)=='u' || *(*(words+i)+j)=='i'))
{
z=1;//最上层
}
if(x+y+z>1)//单词占据超过两行直接跳出
{
break;
}
}
if(x+y+z==1)//如果只占据一行则把它存储到要返回的指针数组中
{
sprintf(buff, "%s", *(words+i));//把该单词存入buff字符串
(*returnSize)++;//要返回的个数加一
rewords=(char **)realloc(rewords, (*returnSize)*sizeof(char *));//重新分配待返回数组rewords的空间大小
*(rewords+k)=malloc(sizeof(buff));//为rewords的该位分配需要存放的空间
memcpy(*(rewords+k), buff, strlen(buff)+1);//把buff存放的数据拷贝到rewords数组
memset(buff, ' ', 51);//把buff清空,方便下次使用
k++;//准备存入下一位
}
}
return rewords;
}