比较两个字符串,用 O(n)时间和恒量空间。
int strcmp(char * p1, char * p2) {
while (*p1 != ‘\0’ && *p2 != ‘ \0’ && *p1 == *p2) {
p1++, p2++;
}
if (*p1 == ‘ \0’ && *p2 == ‘ \0’ ) return 0;
if (*p1 == ‘ \0’ ) return -1;
if (*p2 == ‘ \0’ ) return 1;
return (*p1 - *p2); // it can be negotiated whether the above 3 if’s are
necessary, I don’t like to omit them.
}
每天三道冲刺工作--比较两个字符串,用 O(n)时间和恒量空间。
最新推荐文章于 2016-08-20 15:24:16 发布