1. Description
Write a function to find the longest common prefix string amongst an array of strings.
2. Example
{"a","a","b"} should give "" as there is nothing common in all the 3 strings.
{"a", "a"} should give "a" as a is longest common prefix in all the strings.
{"abca", "abc"} as abc
{"ac", "ac", "a", "a"} as a
3. Code
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="C" active="active"]
char* longestCommonPrefix(char** strs, int strsSize) { int str0_length = strsSize == 0 ? 0 : strlen(strs[0]); int i = 0, is_find = 0; for (; i < str0_length && !is_find; i++ ) { for (int j = 1; j < strsSize && !is_find; j++) { if (strs[0][i] != strs[j][i]) { i--; is_find = 1; } } } char *result = (char*)malloc((i + 1) * sizeof(char)); strncpy(result, strs[0], i); result[i] = '\0'; return result; }
[/restab]
[/restabs]
4.Test
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="C" active="active"]
#includechar* longestCommonPrefix(char** strs, int strsSize) { int str0_length = strsSize == 0 ? 0 : strlen(strs[0]); int i = 0, is_find = 0; for (; i < str0_length && !is_find; i++ ) { for (int j = 1; j < strsSize && !is_find; j++) { if (strs[0][i] != strs[j][i]) { i--; is_find = 1; } } } char *result = (char*)malloc((i + 1) * sizeof(char)); strncpy(result, strs[0], i); result[i] = '\0'; return result; } int main() { char *strs[] = { "a","b" }; puts(longestCommonPrefix(strs, 2)); system("pause"); return 0; }
[/restab]
[/restabs]
Comments | NOTHING