题解 | #最长公共前缀#
最长公共前缀
http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
/**
- 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
- @param strs string字符串一维数组
- @param strsLen int strs数组长度
- @return string字符串
- C语言声明定义全局变量请加上static,防止重复定义
- C语言声明定义全局变量请加上static,防止重复定义 / int cmp(char a, int alen, char* b, int blen, char c) { int cmplen = 0; int len = alen >= blen ? blen : alen; for (int i = 0; i < len; i++) { if (a[i] != b[i]) { break; } c[cmplen++] = a[i]; //printf("%c", c[i]); } // printf(" %d\n", cmplen); return cmplen > len ? len : cmplen; } char longestCommonPrefix(char** strs, int strsLen ) { // write code here int i = 0, j = 0; int max = 0xffff, tmp = 0; char ans = (char)malloc(5000); char strp = (char)malloc(5000); memset(ans, 0, 5000); if (strs == NULL || strsLen == 0) { return ""; } if (strsLen == 1) { return strs[0]; } for (i = 0, j = strsLen - 1; i < j;) { memset(strp, 0, 5000); tmp = cmp(strs[i], strlen(strs[i]), strs[j], strlen(strs[j]), strp); if (max > tmp) { memcpy(ans, strp, 5000); max = tmp; //printf("%d %s\n", max, ans); } strlen(strs[i]) > strlen(strs[j]) ? i++ : j--; } return ans; }