Substring(最长回文串)

本文介绍了一种寻找字符串中最长回文子串的方法,并提供了一个C++实现示例。该算法通过比较原始字符串及其反转字符串来找出最长的回文子串,适用于长度在1到50个字符之间的字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


You are given a string input. You are to find the longest substring of input such that the reversal of the substring is also a substring of input. In case of a tie, return the string that occurs earliest in input. 

Note well: The substring and its reversal may overlap partially or completely. The entire original string is itself a valid substring . The best we can do is find a one character substring, so we implement the tie-breaker rule of taking the earliest one first.

Input

The first line of input gives a single integer, 1 ≤ N ≤ 10, the number of test cases. Then follow, for each test case, a line containing between 1 and 50 characters, inclusive. Each character of input will be an uppercase letter ('A'-'Z').

Output

Output for each test case the longest substring of input such that the reversal of the substring is also a substring of input

Sample Input

3                   
ABCABA
XYZ
XCVCX

Sample Output

ABA
X
XCVCX

AC代码:

#include<bits/stdc++.h>
using namespace std;
string s,ss;
int i,j,k,l;
int N;
int dp[55][55];
void sss(){
	ss="";
	for(i=s.size();i>-1;i--){
		ss+=s[i];
	}	
}
int main()
{
	while(cin>>N){
		while(N--){
			cin>>s;
			memset(dp,0,sizeof(dp));
		    sss();
			k=l=0;
			for(i=1;i<=s.size();i++)
            for(j=1;j<=ss.size();j++){
                if(s[i-1]==ss[j-1]){
                    dp[i][j]=dp[i-1][j-1]+1;
                }
                if(l<dp[i][j]){
                    l=dp[i][j];  //更新 
                    k=i-1;
                }
            }
            for(i=k-l+1;i<=k;i++)
			cout<<s[i];
			cout<<endl; 
		}
	}
	return 0;
}


### 寻找最长回文串的算法实现 #### 中心扩散法简介 中心扩散法是一种用于寻找最长回文子串的有效方法。该方法通过遍历字符串中的每一个字符作为潜在的回文中心,向两侧扩展来找到最大长度的回文子串[^2]。 对于奇数长度的回文串,中心是一个单独的字符;而对于偶数长度的回文串,则存在两个相邻字符组成的中心。为了处理这两种情况,在每次迭代时都需要尝试两种不同的中心位置并记录更长的那个结果。 #### Python代码示例 下面提供了一个基于上述原理编写的Python函数`longest_palindromic_substring()`: ```python def longest_palindromic_substring(s: str) -> str: if not s or len(s) == 0: return "" start, end = 0, 0 for i in range(len(s)): len1 = expand_around_center(s, i, i) len2 = expand_around_center(s, i, i + 1) max_len = max(len1, len2) if max_len > end - start: start = i - (max_len - 1) // 2 end = i + max_len // 2 return s[start:end + 1] def expand_around_center(s: str, left: int, right: int) -> int: L, R = left, right while L >= 0 and R < len(s) and s[L] == s[R]: L -= 1 R += 1 return R - L - 1 ``` 此代码定义了辅助函数 `expand_around_center()`, 它接受三个参数:原始字符串`s`以及表示可能成为回文中点的一对索引值`left` 和 `right`. 函数返回从这对索引向外扩展开来的有效回文部分的最大宽度. 主函数则利用这个工具去计算整个输入字符串内的最佳解,并最终输出对应的字串片段.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值