完美字符串

完美字符串

题干
如果一个字符串中包含了所有 26 个小写字母,则我们认为它是完美字符串。现在给定一个字符串 S,你需要找出它的所有子串中,最短的完美字符串的长度。

输入
输入一行仅包含小写字母的字符串 S(1 <= |S| <= 1e5)。

输出
输出一个整数,代表S满足完美字符串的最短子串的长度。
如果S的子串中没有完美字符串,则输出-1。

输入样例
abccdefghijklmnopqrstuvwxyz

输出样例
27

知识点:双指针、字符串

思路
首先判断该字符串是否存在完美字符串;
第一个思路是两个指针从前到后一次选出每个完美字符串的长度,输出最小完美字符串的长度;
第二个思路是两个指针分别从前面和后面一次缩短字符串长度,最后得到最短的完美字符串。

上代码

#include <string>
#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;
const int N = 130;
int ch[N];
string s;

bool check(int l, int r)
{
	int flag = 1;
	for(int i = l; i <= r; i ++)
	{
		int index = s[i];
		ch[index] = 1;
	}
	for(int i = 97; i <= 122; i ++)
	{
		if(ch[i] == 0) flag = 0;
	}
	for(int i = 97; i <= 122; i ++) ch[i] = 0;
	if(flag == 0) return false;
	else return true;
}

int main()
{
	cin >> s;
	int ans = 1e5 + 100;
	int len = s.size();
	int l = 0, r = len - 1;
	if(check(l, r) == false)
	{
		cout << -1;
		return 0;
	}
	if(len <= 200)
	{
		l = 0, r = 0;
		while(1)
		{
			if(check(l, r) == false) r ++;
			if(check(l + 1, r) == true) l ++;
			if(check(l, r) == true && check(l + 1, r) == false)
			{
				int pre = r - l + 1;
				ans = min(ans, pre);
				l = l + 1;
			}
			if(r == len - 1) break;
		}
	}
	else
	{
		while(1)
		{
			if(check(l, r - 1) == true) r --;
			if(check(l + 1, r) == true) l ++;
			if(check(l, r) == true && check(l + 1, r) == false && check(l, r - 1) == false)
			{
				ans = r - l + 1;
				break;
			}
		}
	}
	if(ans == 100100) cout << -1;
	else cout << ans;
	return 0;
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值