一道在线测试题:给一个二进制字符串str(即只包含0和1的字符),找到其中连续最长0出现的位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
#include <string.h>; #include <stdio.h>; int getLongestZeroPos(char *str, char **start, char **end) { *start=str, *end=str; char *c_start=str, *c_end=str; while(*str!=' ') { while((*str!=' ') && (*str == '0')) ++str; if (c_end!=str) { c_end=str; if ((c_end-c_start)>(*end-*start)) { *end = c_end; *start = c_start; } } while((*str!=' ') && (*str == '1')) c_end=c_start=++str; } if(*end == *start) { *start=NULL; *end=NULL; return 0; } *start++; return *end-*start; } int main(int argc, char* argv[]) { char str[100]; char *start, *end; int len; scanf("%s", str); str[strlen(str)]=' '; len = getLongestZeroPos(str, &start, &end); if(!len) printf("No zero in string %s", str); else printf("The string is %snLongest zero is from %d to %dn", str, start-str, end-str); } |