题解:P12171 [蓝桥杯 2025 省 Python B] 最长字符串
题目大意小蓝想要找到一个最长的优美字符串。
一个长度为
解题思路:
我们可以遍历所有的字符串。如对于任意一个字符串
- 若长度不相等,取最长的。
- 若长度相等,取字典序教小的。
我在这里给出代码框架,检查函数请自行补充完整。
#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;
}
遍历完这几个字符串后输出答案即可。