标签:
一道考察"工程"能力的好题,但是你丫能说明一下规则不。。
用状态机求解:
当遍历完字符串后:
1. 绿色的状态至少要出现1个
2. 红色的状态不能作为终结状态
代码:
1 enum Status { 2 PRE_PADDING, 3 SIGN, 4 NUMBER_BEFORE_POINT, 5 POINT, 6 NUMBER_AFTER_POINT, 7 EXPONENT, 8 EXPONENT_SIGN, 9 EXPONENT_NUMBER, 10 POST_PADDING 11 }; 12 13 bool isNumber(const char *s) { 14 bool mask[10] = {false}; 15 Status state = PRE_PADDING; 16 17 while (*s) { 18 switch (state) { 19 case PRE_PADDING: 20 if (*s == ‘ ‘) mask[state = PRE_PADDING] = true; 21 else if (*s == ‘+‘ || *s == ‘-‘) mask[state = SIGN] = true; 22 else if (*s >= ‘0‘ && *s <= ‘9‘) mask[state = NUMBER_BEFORE_POINT] = true; 23 else if (*s == ‘.‘) mask[state = POINT] = true; 24 else return false; 25 break; 26 case SIGN: 27 if (*s >= ‘0‘ && *s <= ‘9‘) mask[state = NUMBER_BEFORE_POINT] = true; 28 else if (*s == ‘.‘) mask[state = POINT] = true; 29 else return false; 30 break; 31 case NUMBER_BEFORE_POINT: 32 if (*s >= ‘0‘ && *s <= ‘9‘) mask[state = NUMBER_BEFORE_POINT] = true; 33 else if (*s == ‘.‘) mask[state = POINT] = true; 34 else if (*s == ‘e‘) mask[state = EXPONENT] = true; 35 else if (*s == ‘ ‘) mask[state = POST_PADDING] = true; 36 else return false; 37 break; 38 case POINT: 39 if (*s >= ‘0‘ && *s <= ‘9‘) mask[state = NUMBER_AFTER_POINT] = true; 40 else if (*s == ‘e‘) mask[state = EXPONENT] = true; 41 else if (*s == ‘ ‘) mask[state = POST_PADDING] = true; 42 else return false; 43 break; 44 case NUMBER_AFTER_POINT: 45 if (*s >= ‘0‘ && *s <= ‘9‘) mask[state = NUMBER_AFTER_POINT] = true; 46 else if (*s == ‘e‘) mask[state = EXPONENT] = true; 47 else if (*s == ‘ ‘) mask[state = POST_PADDING] = true; 48 else return false; 49 break; 50 case EXPONENT: 51 if (*s >= ‘0‘ && *s <= ‘9‘) mask[state = EXPONENT_NUMBER] = true; 52 else if (*s == ‘+‘ || *s == ‘-‘) mask[state = EXPONENT_SIGN] = true; 53 else return false; 54 break; 55 case EXPONENT_SIGN: 56 if (*s >= ‘0‘ && *s <= ‘9‘) mask[state = EXPONENT_NUMBER] = true; 57 else return false; 58 break; 59 case EXPONENT_NUMBER: 60 if (*s >= ‘0‘ && *s <= ‘9‘) mask[state = EXPONENT_NUMBER] = true; 61 else if (*s == ‘ ‘) mask[state = POST_PADDING] = true; 62 else return false; 63 break; 64 case POST_PADDING: 65 if (*s == ‘ ‘) mask[state = POST_PADDING] = true; 66 else return false; 67 break; 68 default: 69 return false; 70 } 71 s++; 72 } 73 74 return !(state == PRE_PADDING 75 || state == SIGN 76 || state == EXPONENT 77 || state == EXPONENT_SIGN) 78 && (mask[NUMBER_BEFORE_POINT] 79 || mask[NUMBER_AFTER_POINT]); 80 }
标签:
原文地址:http://www.cnblogs.com/boring09/p/4244261.html