题解分享
题解分享简介
回文字符串(编程题) - 题解
```
#include<bits/stdc++.h>
using namespace std;
bool Is_huiwen(string s){
int length = s.length();
for(int i=0,j=length-1;i<=j;i++,j--){
if(s[i]!=s[j]) return false;
}
return true;
}
bool canFormPalindrome(string s){
int n = s.length();
int i =0,j=n-1;
if(Is_huiwen(s)){
return true;
}
//从两端向中间检查
while(i<j){
if(s[i]!=s[j]){
//如果不匹配,检查s[j]是否是可插入的字符
if(s[j]!='l'&&s[j]!='q'&&s[j]!='b'){
return false;// 如果不是可插入的字符,直接返回 No
}
j--;// 如果是可插入的字符,跳过 s[j],继续检查下一个字符
}
else{// 如果匹配,继续向中间移动
i++;
j--;
}
}
return true;
}
int main(){
int N;
cin >> N;
vector<string> strings;
for(int i=0;i<N;i++){
string s;
cin >> s;
strings.push_back(s);
}
for(int i=0;i<N;i++){
if(canFormPalindrome(strings[i])){
cout << "Yes"<<endl;
}
else{
cout << "No"<<endl;
}
}
return 0;
}
```
查看全文
1
0
0
3
回文字符串(编程题) - 题解
```
/*
4种情况
1.字符串s本身回文aaa
2.全为"lqb"字符,补充另一半即可
lqb ==> bql_lqb
3.前部分回文
ioilqb ==> bql_ioilqb
4.部分回文
bioi_blq ==>ql_bioi_blq
*/
#include <iostream>
using namespace std;
bool ishui(string s){
int n = s.size();
for (int i = 0; i < n / 2; ++i) {
if(s[i] != s[n-i-1]){
return false;
}
}
return true;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t;cin >> t;
while(t--){
string s;cin >> s;
int n = s.size();
if(ishui(s)){
cout << "Yes\n";
continue;
}else{
int start_ = 0,end_ = 0;
bool status = true;
for (int i = 0; i < n ; ++i) {
if(s[i] != 'l'&&s[i] != 'q' && s[i] != 'b'){
start_ = i;
status = false;
break;
}
}
if(status) {
cout << "Yes\n";
continue;
}else{
string pre_s = "";
for (int i = n-1; i >= 0 ; i--) {
if(s[i] != 'l'&&s[i] != 'q' && s[i] != 'b'){
end_ = i;
break;
}
}
for (int i = 0; i <= end_ ; ++i) {
pre_s += s[i];
}
if(ishui(pre_s)){
cout << "Yes\n";
continue;
}else{
string mid_s = "";
for (int i = start_; i <= end_; ++i) {
mid_s +=s[i];
}
if(ishui(mid_s)){
string left_s = "",right_s = "";
for (int i = start_ -1; i >= 0 ; i--) {
left_s += s[i];
}
for (int i = end_ + 1 ; i <= n ; i++) {
right_s += s[i];
}
for (int i = 0; i < left_s.size(); ++i) {
if(left_s[i] !=right_s[i]){
cout << "No\n";
break;
}else if(i == left_s.size()-1){
cout << "Yes\n";
}
}
}else{
cout << "No\n";
continue;
}
}
}
}
}
return 0;
}
```
查看全文
1
0
0
1



