10000的随机数组由ox组成,查找数组中oox...x(任意x)oox....x(任意x)o的个数
enum { DATA_SIZE = 10000, }; enum enum_status { STATUS_FOUND = 0, STATUS_ERR, STATUS_NOT_FOUND, //ALL 'X' }; enum_status findOOX(int data[DATA_SIZE], int start, int& index) { for(int i = start; i < DATA_SIZE - 2; i++) { if(data[i] == 'O' && data[i + 1] == 'O' && data[i + 2] == 'X') { index = i; return STATUS_FOUND; } if(data[i] == 'O' && (data[i + 1] != 'O' || data[i + 2] != 'X')) { index = i; return STATUS_ERR; } } return STATUS_NOT_FOUND; } bool findO(int data[DATA_SIZE], int start, int& index) { for(int i = start; i < DATA_SIZE; i++) { if(data[i] == 'O') { index = i; return true; } } return false; } int test_main(int data[DATA_SIZE]) { enum_status stat = STATUS_NOT_FOUND; int count = 0; int index = 0; for(int i = 0; i < DATA_SIZE; i++) { stat = findOOX(data, i, index); if(stat == STATUS_NOT_FOUND) { break; } if(stat == STATUS_ERR) { i = index; //TODO continue; } i = index + 3; stat = findOOX(data, i, index); if(stat == STATUS_NOT_FOUND) { break; } if(stat == STATUS_ERR) { i = index; //TODO continue; } i = index + 3; if(findO(data, i, index)) { count++; i = index; } else { break; } } return count; }
用于生成测试用例的demo:
#include <stdio.h> #include <stdlib.h> #define SIZE 10000 int test_main(int data[SIZE]); static int data[SIZE]; static void build_data(void) { for (int a = 0; a < SIZE; a++) { data[a] = (rand() % 2) ? 'O' : 'X'; } } void main(void) { for (int l = 0; l < 10; l++) { build_data(); printf("%d ", test_main(data)); } system("pause"); }