2 条题解

  • 0
    @ 2025-10-3 15:35:38

    在发表我自己的题解前,我先说一下字符串作为字符数组的比较标准的写法,以此能让人更正确地理解字符串的本质。

    字符串实际上是以'\0'结尾的字符数组。什么意思呢,就是像下面这样:

    char str1[10] = "apple";
    char str2[10] = {'a', 'p', 'p', 'l', 'e', '\0'};
    

    上面两种定义字符串的方式是等价的,如果字符数组的字符后面没有'\0',那它实际上就只是普通的字符数组,而不是字符串了。

    我的解题方法是用kmp。这道题用这个可能是杀鸡用牛刀了,但从简单题着手,尝试使用对于我自己来说比较难理解的算法,不妨是一种学习方式呢?

    对字符串匹配也有兴趣的话,可以试试去搜一下kmp算法!我的代码如下:

    #include <stdio.h>
    #include <string.h>
    
    int kmp_search(char str[], char sound[], int next[]) {
    	
    	int i = 0;
    	int j = 0;
    	while (i < strlen(str)) {
    		if (sound[j] == str[i]) {
    			i ++;
    			j ++;
    		} else if (j >= 1) {
    			j = next[j - 1];
    		} else {
    			i ++;
    		}
    		
    		if (j == strlen(sound)) {
    			return 1;
    		}
    	}
    	
    	return 0;
    }
    
    int main() {
    	char str[105] = {0};
    	char xuebao_sound[9] = "awaw";
    	char sheli_sound[9] = "yaya";
    	int next_x[9] = {0, 0, 1, 2};
    	int next_s[9] = {0, 0, 1, 2};
    	
    	scanf("%s", str);
    	
    	int flag1 = kmp_search(str, xuebao_sound, next_x);
    	int flag2 = kmp_search(str, sheli_sound, next_s);
    	
    	if (flag1 == 1) {
    		printf("zhishixuebao");
    	} else if (flag2 == 1) {
    		printf("zhishisheli");
    	}
    	
    	return 0;
    }
    

    然后,感谢孚损2提供的题解,让我学到了fgets()和其它一些字符串处理函数的用法,下面是我仿照你的思路写的代码:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
    	int length;
    	scanf("%d", &length);
    	
    	char str[105];
    	fgets(str, 101, stdin); // 从键盘获取输入,不过fgets()会获取换行符,之后要注意切掉 
    	
    	// 如果有换行符,就把它替换掉,strcspn()就是来获取'\n'位置的
    	str[strcspn(str, "\n")] = '\0';
    	
    	char xuebao_sound[9] = "awaw";
    	char sheli_sound[9] = "yaya";
    	
    	int n = strlen(str);
    	for (int i = 0; i <= (n - 4); i ++) {
    		if (strncmp(&str[i], xuebao_sound, 4) == 0) {
    			printf("zhishixuebao");
    		} else if (strncmp(&str[i], sheli_sound, 4) == 0) {
    			printf("zhishisheli");
    		}
    	}
    	
    	return 0;
    }
    

    信息

    ID
    53
    时间
    1000ms
    内存
    256MiB
    难度
    4
    标签
    递交数
    296
    已通过
    137
    上传者