牛客——第十八届浙大城市学院程序设计竞赛(同步赛)F题Palindrome

链接: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;
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值