UVa 902 - Password Search

题目:给你一个小写字母组成大的串和一个整数n。找到里面长度为n出现最频繁的子串。

分析:字符串、hash表、字典树。

这里使用hash函数求解,仅仅做一次扫描就可以。

说明:假设频率同样输出字典序最小的。

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>

char subs[15],buf[1000001];
char *strsub(char *str, int n)
{
	for (int i = 0 ; i < n ; ++ i)
		subs[i] = str[i];
	subs[n] = 0;
	return subs;
}

//hash_define
typedef struct node0  
{  
    char  name[15];
	int   count;  
    node0*next;  
}hnode;  
hnode* hash_head[1000000];  
hnode  hash_node[1000000];  
int    hash_size;  
  
void hash_init()  
{  
    hash_size = 0;  
    memset(hash_node, 0, sizeof(hash_node));  
    memset(hash_head, 0, sizeof(hash_head));  
}  

void hash_insert(char* str)  
{  
    int value = 0;
    for (int i = 0 ; str[i] ; ++ i)
    	value = (value*10+str[i]-'a')%1000000;
    
    for (hnode* p = hash_head[value] ; p ; p = p->next)  
        if (!strcmp(str, p->name)) {
			p->count ++;
			return;  
        }
    strcpy(hash_node[hash_size].name, str);
    hash_node[hash_size].count = 1;
    hash_node[hash_size].next = hash_head[value];  
    hash_head[value] = &hash_node[hash_size ++];     
}

void hash_max()
{
	int max = 0;
	for (int i = 1 ; i < hash_size ; ++ i) 
		if (hash_node[max].count == hash_node[i].count) {
			if (strcmp(hash_node[max].name, hash_node[i].name) > 0)
				max = i;
		}else if (hash_node[max].count < hash_node[i].count)
			max = i;
	printf("%s\n",hash_node[max].name);
}
//hash_end

int main()
{
	int n;
	while (~scanf("%d%s",&n,buf)) {
		hash_init();
		int end = strlen(buf)-n;
		if (end < 0) continue;
		for (int i = 0 ; i <= end ; ++ i)
			hash_insert(strsub(&buf[i], n));
		
		hash_max();
	}
    return 0;
}


转载于:https://www.cnblogs.com/gccbuaa/p/7399868.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值