1160. 拼写单词 C语言(期间发现数组地址越界报错花了很多时间--指针还是难)

//设计思路 先遍历一遍char字符串 单个字母为key 出现的次数为value 得到数组A、
//遍历字母表的各个字符串。只有字符串的所有的元素都在char数组中都存在---并且每次遍历都字符只能使用一次
//使用完成版之后需要对A进行还原 还原成为char的初始状态
//能够全部找到的才需返回输出

虽然简单题 自己设计完成 发现了一些问题
一直提示地址错误而且提示的位置与需要修改的位置不一致
提示位置:

while (*tmp != '\0'){

实际需要修改的位置使用指针表示的二维数组中的字符串:
原因是leetcode提供的测试用例是数组形式的不是指针的类型 出现地址越界

while ((*words)[i] != NULL){

修改后:

for (int x = 0; x < wordsSize; x++){
int countCharacters(char ** words, int wordsSize, char * chars){

	int *num = (int*)malloc(sizeof(int)* 26);//用来统计字符串中各个元素出现的次数
	for (int t = 0; t < 26; t++){
		num[t] = 0;
	}
	while (*chars != '\0'){
		num[*chars - 'a']++;
		chars++;
	}
	int i = 0;//遍历单词表用
	int length = 0;//统计符合要求的所有单词的字母数

	for (int x = 0; x < wordsSize; x++){

		int *arr = (int*)malloc(sizeof(int)* 26);//重置使用过的字母表
		for (int i = 0; i < 26; i++){
			arr[i] = num[i];
		}

		int b = 0;
		int middlelength = 0;//是否符合要求的标志
		char *second = *words;
		while (*second != '\0'){   //统计单个单词
			//	second = (char)malloc(sizeof(char));
			arr[*second - 'a']--;
			printf("%c", *second);
			if (arr[*second - 'a'] < 0){
				b = 1;
				break;
			}
			middlelength++;
			second++;
		}
		if (b == 0){
			length = length + middlelength;
		}
		b = 0; middlelength = 0;//将统计数值重置为0
		words++;
	}
	return length;
}
发布了212 篇原创文章 · 获赞 32 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_42664961/article/details/104305410