Dominant Character 思维,字符串,贪心

在这里插入图片描述
题意 :

  • 给一abc字符串,要求找出长度最短的子串 s m a l l e s t s u b s t r i n g smallest substring smallestsubstring(本题的阴间之处,不是找最小的子串的长度),满足长度至少为2,a的个数严格大于b且c的个数

思路 :

  • 最终答案的开头和结尾一定是’a’,其它的只会更差
  • 求最小的子串,可以感觉到这个题比较巧,而且随着子串变长,要求是越来越难达到的(或者有更短更优的),到一定长度后就没有符合的字符串了,发现这个临界是4
  • 以a的个数分类 :当a的数量为2个时,有…符合,3时,有…符合,当a的个数是4时,发现没有满足条件的字符串是最优解
  • 因此,一共七种情况,直接搜索即可
  • s t r i n g string string f i n d find find函数找不到返回的是-1
#include <iostream>
#include <algorithm>
#include <vector>
#define pb push_back
#define endl '\n'

using namespace std;

string ans[] = {
    
    "aa", "aba", "aca", "abca", "acba", "abbacca", "accabba"};

int main()
{
    
    
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    
    int _;
    cin >> _;

    while (_ -- )
    {
    
    
        int n;
        string s;
        cin >> n >> s;
        
        int res = -1;
        for (int i = 0; i < 7; i ++ )
            if (s.find(ans[i]) != -1)
            {
    
    
                res = ans[i].size();
                break;
            }
        
        cout << res << endl;
    }
    
    return 0;
}

おすすめ

転載: blog.csdn.net/m0_51448653/article/details/121403188