SDUT OJ 2892 A (字典树问题-输出出现次数最多的字符串的出现次数,60ms卡时间,指针+最后运行完释放内存)

A

 

Time Limit: 60ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

给出n(1<= n && n <= 2*10^6)个字符串,每个字符串只包含小写英文字母,且最多有五个。问这n个字符串中出现次数最多的有多少个。

输入

单组输入。第一行输入一个数字n,接下来n行,每行包含一个字符串。

输出

输出一个数字代表答案。

示例输入

5

aba

abb

w

aba

z

示例输出

2


释放内存与不释放内存的区别:

代码:

#include <stdio.h>

#include <string.h>

#include <stdlib.h>



struct Trie

{

	int flag;

	struct Trie *next[26];

}*temp;



struct Trie *newnode()

{

	Trie *p;

	int i;

	p=new struct Trie;

	for(i=0; i<26; i++)

	{

		p->next[i]=NULL;

	}

	p->flag=0;

	return p;

}



int max=0;

void Insert(struct Trie *root, char *s )

{

	int i;

	int len=strlen(s);

	struct Trie *p; p=root;



	for(i=0; i<len; i++)

	{

		int t=s[i]-'a';

		if(p->next[t]==NULL )

		{

			temp = newnode();

			p->next[t]=temp;

		}

		p=p->next[t];

	}

	p->flag++;

      	if(p->flag > max )

	{

		max = p->flag;

	}

}



void Shanchu(struct Trie *p)

{

    int i;

    for(i=0; i<26; i++)

    {

        if(p->next[i]!=NULL )

        {

            Shanchu(p->next[i]); //递归进行内存清理删除

        }

    }

    free(p);

}



int main()

{

    int n;

	int i;

	char s[6];

	scanf("%d%*c", &n);

	Trie *trie;

    trie = newnode();

	while(n--)

	{

		scanf("%s", s);

		Insert(trie, s);

	}

	printf("%d\n", max );

    //清理释放内存

    Shanchu(trie);



    return 0;

}

 
   

 

 
  

你可能感兴趣的:(字符串)