虽然为水题,但是我的算法还是比较一般。思想是切分单词的思想,确定切分开始条件,结束条件,在[b,e)之间就是所得单词,因为单词以X作为间隔,为了保证算法正确性,需要在末尾添加X。算法如下
1 #include <stdio.h>
2 #include <string.h>
3 #define MAXN 86
4 int main() {
5
6 int n;
7 char buf[MAXN] = {0};
8 scanf("%d", &n);
9 typedef enum {
10 WordIn,
11 WordOut,
12 } Word;
13 while ( n--> 0) {
14
15 scanf("%s", buf);
16 int sum = 0, b = 0, e = 0, len = strlen(buf);
17 buf[len++] = 'X', buf[len] = '\0';
18 Word word = WordOut;
19
20 // 遍历字符串
21 for (int i = 0; buf[i]; i++) {
22
23 // 记录单词开头
24 if (buf[i] == 'O') {
25
26 b = word == WordOut? ( word = WordIn, i) : b;
27
28 }else {
29
30 // 记录单词结尾,并作统计
31 if (word == WordIn) {
32 word = WordOut;
33 e = i;
34 int max = e - b;
35 sum += max*(max + 1) / 2;
36 }
37
38 }
39 }
40 printf("%d\n", sum);
41 }
42 return 0;
43 }
by sixleaves