#include <bits/stdc++.h>
using namespace std;
string s,x;
int n,l,r;
int main(){
cin>>s>>n;
for(int i=1;i<=n;i++){
cin>>l>>r;
int sx=-1;
bool aa=true;
for(int j=l-1;j<r;j++)
{
sx++;
x[sx]=s[j];
// cout<<s[j]<<x[sx]<<sx;
if(s[j]!='a') aa=false;
}
if(aa==true)
{
cout<<"NULL"<<endl<<"Happy Chinese New Year!"<<endl;
continue;
}
for(int j=sx;j>=0;j--)
{
if(x[j]=='a') x[j]='z';
else {
x[j]--;
break;
}
}
for(int j=0;j<=sx;j++) cout<<x[j];
cout<<endl;
if(s.find(x)!=string::npos) cout<<"Happy New Year!"<<endl;
else cout<<"Happy Chinese New Year!"<<endl;
}
}
把题目贴出来看下。
我搜索出来只有一个涂色的,和你的这个也不一样啊
不知道你这个问题是否已经解决, 如果还没有解决的话:首先,我们可以看到这段代码存在一些潜在的问题和可以优化的空间。
x
没有初始化,直接赋值可能会导致 undefined behavior。find
函数查找是否存在字符串 x
,时间复杂度较高。下面是优化后的代码:
#include <bits/stdc++.h>
using namespace std;
int main(){
string s, x;
int n;
cin >> s >> n;
for (int i = 1; i <= n; i++){
int l, r;
cin >> l >> r;
x = s.substr(l - 1, r - l + 1);
if (x == string(x.size(), 'a')){
cout << "NULL" << endl << "Happy Chinese New Year!" << endl;
}
else{
bool hasHappyNewYear = false;
for (int j = x.size() - 1; j >= 0; j--){
if (x[j] == 'a') {
x[j] = 'z';
}
else{
x[j]--;
hasHappyNewYear = true;
break;
}
}
cout << x << endl;
if (hasHappyNewYear){
if (s.find(x) != string::npos){
cout << "Happy New Year!" << endl;
}
else{
cout << "Happy Chinese New Year!" << endl;
}
}
else{
cout << "NULL" << endl << "Happy Chinese New Year!" << endl;
}
}
}
return 0;
}
优化方案: - 使用 substr
函数代替 for 循环来生成子串 x
,避免了多次复制和拼接操作,提高了效率。 - 添加标志位 hasHappyNewYear
,减少了对字符串 x
是否为全 a
的判断次数。 - 在第二个条件判断前添加一个判断,如果 x
不含有 'a',则直接输出结果,并且跳过第二个条件的判断。
希望以上优化代码和解释能够帮助到你!如果有其他问题需要解答,请随时提问。