文章

7

粉丝

502

获赞

2

访问

13.1k

头像
题目1320 统计字符
我要提问
发布于2024年1月11日 21:37
阅读数 216

明明编译器输出的是正确值,但是OJ判断我输出超时surprise

#include <stdio.h>
#include <string.h>

char s[100];
char t[100];

int main() {
    while (1) {
        fgets(s, sizeof(s), stdin);
        if (s[0] == '#' || s[0] == '\n') // 检查是否为 '#' 或空行以退出
            break;

        fgets(t, sizeof(t), stdin);

        int ls = strlen(s);
        int lt = strlen(t);

        // 从字符串中去除换行符
        if (s[ls - 1] == '\n')
            s[--ls] = '\0';

        if (t[lt - 1] == '\n')
            t[--lt] = '\0';

        for (int i = 0; i < ls; i++) {
            int cnt = 0;
            for (int j = 0; j < lt; j++) {
                if (s[i] == t[j])
                    cnt++;
            }
            printf("%c %d\n", s[i], cnt);
        }
    }
    return 0;
}

登录查看完整内容


登录后发布评论

3 条评论
snake VIP
2024年1月12日 19:23

把第一个输入写到while里,这样读到文件末尾时会自动结束。

修改代码如下

#include <stdio.h>
#include <string.h>

char s[100];
char t[100];

int main() {
    while (fgets(s, sizeof(s), stdin)) {
        if (s[0] == '#' || s[0] == '\n') // 检查是否为 '#' 或空行以退出
            break;

        fgets(t, sizeof(t), stdin);

        int ls = strlen(s);
        int lt = strlen(t);

        // 从字符串中去除换行符
        if (s[ls - 1] == '\n')
            s[--ls] = '\0';

        if (t[lt - 1] == '\n')
            t[--lt] = '\0';

        for (int i = 0; i < ls; i++) {
            int cnt = 0;
            for (int j = 0; j < lt; j++) {
                if (s[i] == t[j])
                    cnt++;
            }
            printf("%c %d\n", s[i], cnt);
        }
    }
    return 0;
}

 

赞(1)

冷喵 : 回复 snake: AC了!!!

2024年1月13日 22:41
冷喵 VIP
2024年1月11日 21:38

赞(0)