In the Leetcode Longest Common Prefix problem solution in C programming 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 “”.
Leetcode Longest Common Prefix problem solution in C programming
char * longestCommonPrefix(char ** strs, int strsSize){
int min_str = 200;
int index;
if(strsSize == 0)
return "";
if(strsSize < 0 || strsSize > 200)
return NULL;
//Find the shortest string
for(int j=0; j<strsSize; j++){
if(strlen(strs[j]) < min_str){
min_str = strlen(strs[j]);
index = j;
}
}
for(int i=0; i<min_str; i++){
for(int j=0; j<strsSize; j++){
if(strs[index][i] != strs[j][i]){
strs[index][i] = '\0';
goto ret;
}
}
}
ret:
return strs[index];
}
Also read,
- Leetcode Longest Common Prefix problem solution in C++
- Leetcode Longest Common Prefix problem solution in Java
- Leetcode Longest Common Prefix problem solution in Python
- Leetcode Longest Common Prefix problem solution in C#