NC18386 字符串

题目地址:

https://ac.nowcoder.com/acm/problem/18386

基本思路:

比较明显的一个尺取,枚举左指针,然后将右指针向后试探,记录个字母的出现次数,每次一下子串是否合法,取合法子串的最短长度就好了。

参考代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define int long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF (int)1e18

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
  return neg * x;
}
inline void print(int x) {
  if (x < 0) { putchar('-'); x = -x; }
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}

int n;
string s;
int memo[26];
bool check() {
  for (int i = 0; i < 26; i++) if (memo[i] <= 0) return false;
  return true;
}
signed main() {
  IO;
  cin >> s;
  n = s.size();
  int r = 0, ans = INF;
  mset(memo, 0);
  for (int l = 0; l < n; l++) { //枚举左指针;
    while (r < n) {//试探右指针;
      if (check()) break;
      memo[s[r++] - 'a']++;
    }
    //取最短合法长度就行了;
    if (check()) { int res = r - l; ans = min(ans, res); }
    memo[s[l] - 'a']--;
  }
  cout << ans << '\n';
  return 0;
}