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

· · 题解

题目传送门

题目分析:

做法:这题就是找出最长的字符串,我们可以通过判断输入的与我们目前存储的答案进行比较得出答案。

比较字符串长度的方法:

size 函数可以返回一个字符串的长度。

比较字典序的方法:

字符串可以直接比较字典序。

C++ 代码如下:

#include<iostream>
#include<cstring>
using namespace std;
string ans="";
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr); // 关闭同步流 
string s;
while(cin>>s){ // 连续输入 
if(s.size()>ans.size()){ // 比较长度 
ans=s;
}
else if(s.size()==ans.size()&&s>ans){ // 先要确保长度相等再判断字典序 
ans=s;
}
}
cout<<ans<<'\n';
return 0;
}

AC 记录