跳到正文

个人记录

总结

zzilin约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年8月27日
收录
2026年8月27日
更新
2026年8月27日
篇幅
约 2 分钟

版本

  1. v1当前

P13867

题意:给定一个字符串,求这个字符串中第一个最短唯一子串。

思路:因为子串越短就越难唯一,所以有单调性,考虑二分答案。check时只需要记录那个长度的子串的每个哈希值有多少个,再找第一个哈希值只有一个的子串即可。

代码:

C++
#include<bits/stdc++.h>
#define ull unsigned long long
using namespace std;
const ull base=13331;
string s,ss;
int n;
ull hs[300005],pw[300005];
unordered_map<ull,int> mp;
ull get_hs(int l,int r)
{
	return hs[r]-hs[l-1]*pw[r-l+1];
}
bool check(int x)
{
	for(int i = 1;i <= n-x+1;i++)
	{
		mp[get_hs(i,i+x-1)]++;
	}
	for(int i = 1;i <= n-x+1;i++)
	{
		if(mp[get_hs(i,i+x-1)]==1)
		{
			ss=s.substr(i,x);
			return true;
		}
	}
	return false;
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin>>s;
	n=s.size();
	s=" "+s;
	pw[0]=1;
	for(int i = 1;i <= n;i++)
	{
		pw[i]=pw[i-1]*base;
		hs[i]=hs[i-1]*base+s[i];
	}
	int l=0,r=n+1;
	while(l+1<r)
	{
		int mid=(l+r)/2;
		if(check(mid))
		{
			r=mid;
		}                                                        
		else
		{
			l=mid;
		}
	}
	cout<<ss;
	return 0;
}
原文