leetcode 第184场周赛第一题(数组中的字符串匹配)

 一、函数的运用

1,strstr(a,b);

判断b是否为a的子串,如果是,返回从b的开头开始到a的结尾

如“abcdefgh” “de”

返回“defgh”;

如果不是子串,返回NULL;

2,memcpy(a,b+n,c);

将b串从第n位后的c个字符串复制到a中

(注:做完函数后需要添加上b[c] = '\0')

返回a串;

二、malloc开辟二维字符串;

首先开辟一个指向字符串指针的指针;

char **arr = (char**)malloc(sizeof(char*)*wordsSize);

等判断出适合题目的子串后

再开辟一个字符串指针

arr[cnt] = (char*)malloc(sizeof(char)*(strlen(words[i])+1));

最后代码如下

 1 char ** stringMatching(char ** words, int wordsSize, int* returnSize){
 2     int cnt = 0;
 3     char **arr = (char**)malloc(sizeof(char*)*wordsSize);
 4     for(int i = 0; i < wordsSize; i++)
 5     {
 6         for(int j = 0; j < wordsSize; j++)
 7         {
 8             if(i != j)
 9             {
10                 if(strstr(words[j],words[i]) != NULL)
11                 {
12                     arr[cnt] = (char*)malloc(sizeof(char)*(strlen(words[i])+1)); 
13                     memcpy(arr[cnt], words[i], strlen(words[i])+1);
14                    //上面两行+1是为了多开辟一个空间给arr[cnt]存下words[i]字符串后末尾的'\0'
15                    //因为strlen函数返回的长度是不包含'\0'的长度
16                    //且memcpy返回的arr在字符串结束后最后一位是没有'\0'
17                    //一定要记住加'\0'!!不然会越界! 
18                     cnt++;
19                     break;
20                 }
21             }
22         }
23     }
24     *returnSize = cnt;
25     return arr;
26 
27 
28 }

 (希望下次easy题不要再抄作业了 ̄ω ̄)

猜你喜欢

转载自www.cnblogs.com/luoyoucode/p/12688777.html
今日推荐