题解:P12171 [蓝桥杯 2025 省 Python B] 最长字符串

· · 题解

题目大意小蓝想要找到一个最长的优美字符串。

一个长度为 n 的字符串 s = c_1c_2 \cdots c_n 是优美字符串,必须满足 s 在单词本中,且满足以下两个条件之一:

解题思路: 我们可以遍历所有的字符串。如对于任意一个字符串 s 而言,如果长度为 |s|-1 的字符串也是优美字符串,我们就需要比较长度。在比较长度时,有以下两点。

我在这里给出代码框架,检查函数请自行补充完整。

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxn=1e6+5;
string s[maxn];
int cnt=0;
bool check(string s){//检查字符串s是否为优美字符串

}
void work(){
    string x;
    string ans="";
    while(cin>>x){
        s[++cnt]=x;
    }
    string ans="";
    for(int i=cnt;i>=1;i--){//遍历字符串,我在这里是倒序遍历
        if(check(s[i]){
            if(s[i].size()>ans.size()|||(s[i].size()==ans.size()&&s[i]<ans)){//比较长度及字典序
                ans=s[i];
            }
        }
    }
    cout<<ans;
    return ;
}
signed main(){
    int T=1;
    while(T--){
        work(); 
    }
    return 0;
}

遍历完这几个字符串后输出答案即可。