12/28 每日C 共同前綴 (使用strdup())
Solved
Easy
Topics
Companies
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"] Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i]consists of only lowercase English letters.
char* longestCommonPrefix(char** strs, int strsSize) {
if (strsSize==0)
return "";
char *ptr=strdup(strs[0]); // 使用strdup复制字符串
printf("看看strdup()=%s",ptr);
int i,c=0,j;
for(i=1;i<strsSize;i++)
{
j=0;
while(ptr[j]!='\0' && ptr[j]==strs[i][j] && strs[i][j] != '\0')
{j++;}
//迴圈停止表示結束或者遇到不同的
ptr[j] = '\0';
if (ptr[0]=='\0')
{//表示沒有共同
return "";
}
}
return ptr;
}
!!!!!!!!注意 \0 要使用單引號
#介紹 strdup()
strdup()函數用於複製一個字符串,並回傳一個指向新字符串的指針, 這個函數會使用malloc()動態分配記憶體
,這意味著需要在使用完strdup返回的字符串後手動釋放內存
char *strdup(const char *s)
strdup 接受一个字符串 s 作为参数,返回一个指向新字符串的指针。如果内存分配失败,strdup 返回 NULL。
0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁