链接:https://ac.nowcoder.com/acm/contest/12986/F
来源:牛客网
F题Palindrome
题目描述
You are given a string s of n lowercase letters.
You have to delete exactly two letters from s , determine whether the string can become a palindrome after the change.
Definition of palindrome: If a string s of n lowercase letters is a palindrome, then for each si(1<=i<=n),
s[i]=s[n-i]+1
For example, “ababa” and “abba” are palindromes, but “abab” not.
输入描述:
The first line contains an integer t(1<=t<=10^3) — the number of test cases.
For each test case, the first line contains an integer n(3<=n<=2*10^3) representing the length of s , the second line contains a string of length n .
It is guaranteed that the sum of n for all test cases does not exceed 10^4 .
输出描述:
If it is possible to change the string into a palindrome after deleting two letters from s , please output “Yes”, otherwise output “No”.
示例1
输入
3
4
abca
6
ababab
6
abcabc
输出
Yes
Yes
No
思路:刚开始我直接一步一步往里面套,然后把自己给绕晕了。正确做法用双指针一个从头开始,一个从尾开始,递归到不一样的就判断删除左边字符的或右边的字符可以使字符串为回文。因为题目中需要删除两个字符,所以需要重复做两次动作判断就可,用递归是个明智的选择。
正确代码(非递归):
待写(绕进去还没出来)。。。
正确代码(递归):
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
int f=0;
void dfs(string s,int left,int right,int delet){
if(delet>2){
return;
}
if(left>=right&&delet<=2){
f=1;
return;
}
if(s[left]==s[right]){
dfs(s,left+1,right-1,delet);
}
else{
dfs(s,left,right-1,delet+1);
dfs(s,left+1,right,delet+1);
}
}
int main(){
ios::sync_with_stdio(false);
int t,n;
string s;
while(cin>>t){
while(t--){
cin>>n;
cin>>s;
f=0;
dfs(s,0,n-1,0);
if(f){
cout<<"Yes"<<endl;
}
else{
cout<<"No"<<endl;
}
}
}
return 0;
}