UVA-11404-Palindromic Subsequence(最长公共子序列变形)

本文介绍了一种求解给定字符串中最长回文子序列的方法,通过寻找原串与其反转串之间的最长公共子序列来实现,并确保输出字典序最小的回文串。文章提供了详细的算法思路和完整的C++代码实现。

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

A Subsequence is a sequence obtained by deleting zero or more characters in a string. A Palindrome is
a string which when read from left to right, reads same as when read from right to left. Given a string,
find the longest palindromic subsequence. If there are many answers to it, print the one that comes
lexicographically earliest.
Constraints
• Maximum length of string is 1000.
• Each string has characters ‘a’ to ‘z’ only.
Input
Input consists of several strings, each in a separate line. Input is terminated by EOF.
Output
For each line in the input, print the output in a single line.
Sample Input
aabbaabb
computer
abzla
samhita
Sample Output
aabbaa
c
aba
aha

题意:给定一个字符串,求出去掉某些字符后的最长回文串,如果长度相同则输出字典序最小的回文串。

思路:原串翻转后和原串的最长公共子序列就是最长回文串。状态转移时可以处理字典序最小问题。,这样转移也会导致得到的公共序列并不一定就是回文串,但是可以保证前半部分公共序列一定是回文串的前半部分,所以输出结果的时候注意根据公共序列长度的奇偶选择重复两次输出前半部分就好。
例如: kfclbckibbibjccbej
原串和反串得到的公共序列却是bcibbibc
就因为状态转移的时候按照字典序决定。

状态转移如下
如果s1[i]==s2[j] DP[i][j].len=DP[i-1][j-1].len+1,DP[i][j].str=DP[i-1][j-1].str+s1[i];
否则在DP[i-1][j],DP[i][j-1]中选择长度最大,字典序最小的转移到DP[i]][j]

代码

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
using namespace std;
//最长公共子序列
const int maxn=1005;
struct node
{
    int len;
    string str;
} DP[maxn][maxn];
char str_1[maxn];
char str_2[maxn];
int main()
{
    while(scanf("%s",str_1+1)!=EOF)
    {
        int len=strlen(str_1+1);
        memset(str_2,'\0',sizeof(str_2));
        for(int i=1,j=len; i<=len; i++,j--)
            str_2[i]=str_1[j];//逆置字符串
        for(int i=1; i<=len; i++)
        {
            for(int j=1; j<=len; j++)
            {
                DP[i][j].len=0;
                DP[i][j].str.clear();
            }
        }
        for(int i=1; i<=len; i++)
        {
            for(int j=1; j<=len; j++)
            {
                if(str_1[i]==str_2[j])
                {
                    DP[i][j].len=DP[i-1][j-1].len+1;
                    DP[i][j].str=DP[i-1][j-1].str+str_1[i];
                }
                else
                {
                    if(DP[i-1][j].len>DP[i][j-1].len)
                    {
                        DP[i][j].len=DP[i-1][j].len;
                        DP[i][j].str=DP[i-1][j].str;
                    }
                    else if(DP[i-1][j].len==DP[i][j-1].len)
                    {
                        DP[i][j].len=DP[i-1][j].len;
                        if(DP[i-1][j].str>DP[i][j-1].str)
                            DP[i][j].str=DP[i][j-1].str;
                        else
                            DP[i][j].str=DP[i-1][j].str;
                    }
                    else
                    {
                        DP[i][j].len=DP[i][j-1].len;
                        DP[i][j].str=DP[i][j-1].str;
                    }
                }
            }
        }
//        cout<<DP[len][len].str<<endl;
        if(DP[len][len].len%2==0)
        {
            for(int i=0; i<DP[len][len].len/2; i++)
                printf("%c",DP[len][len].str[i]);
        }
        else
        {
            for(int i=0; i<=DP[len][len].len/2; i++)
                printf("%c",DP[len][len].str[i]);
        }
        for(int i=DP[len][len].len/2-1; i>=0; i--)
            printf("%c",DP[len][len].str[i]);
//        for(int i=0; i<DP[len][len].len; i++)
//            printf("%c",DP[len][len].str[i]);
        printf("\n");
        memset(str_1,'\0',sizeof(str_1));
    }
    return 0;
}
### 使用 Rabin-Karp 算法结合二分法查找最长回文子串 为了找到给定字符串中的最长回文子串,可以采用一种组合策略:利用二分查找来决定可能的最大长度,并通过哈希函数验证该长度下的子串是否为回文。这种方法能够有效地减少不必要的比较次数。 #### 基本思路 1. 定义一个辅助函数 `is_palindrome` 来判断指定位置和长度的子串是不是回文; 2. 对于每一个潜在的中心点(单字符或双字符),尝试扩展到最大范围内的回文; 3. 利用二分查找技术,在已知最小值0和当前发现的最大回文字串长度之间进行搜索; 4. 在每次迭代过程中应用Rabin-Karp算法快速检测是否存在相同长度的不同起始位置但具有相等哈希值的子串;如果找到了,则进一步确认这些候选者确实是回文并更新最优解。 下面是一个Python实现的例子: ```python def rabin_karp_hash(s, p=1_000_000_007, a=256): """计算字符串s基于质数p以及基数a的滚动散列""" hash_value = 0 for char in s: hash_value = (hash_value * a + ord(char)) % p return hash_value def check_palindrome(text, length): """检查text中是否有length长度的回文子串.""" if not text or len(text) < length: return False MOD = 1_000_000_007 BASE = 256 powerL = pow(BASE, length-1, MOD) hashes = set() current_hash = rabin_karp_hash(text[:length], MOD, BASE) for i in range(len(text)-length+1): if str(text[i:i+length]) == str(text[i:i+length])[::-1]: return True next_char_index = i + length if next_char_index < len(text): current_hash = ((current_hash - ord(text[i]) * powerL) * BASE + ord(text[next_char_index])) % MOD while current_hash < 0: current_hash += MOD if current_hash in hashes and \ str(text[i+1:i+length+1]) == str(text[i+1:i+length+1])[::-1]: return True else: hashes.add(current_hash) return False def longest_palindromic_substring_with_rk_and_binary_search(s): lo, hi = 0, len(s)+1 best_len = 0 result = "" while lo <= hi: mid = (lo + hi)//2 found = check_palindrome(s, mid) if found: best_len = max(best_len, mid) result = get_any_palindrome_of_length(s, mid) lo = mid + 1 else: hi = mid - 1 return result def get_any_palindrome_of_length(s, l): n = len(s) for start in range(n-l+1): substr = s[start:start+l] if substr == substr[::-1]: return substr raise ValueError(f"No palindrome of length {l} exists.") ``` 此代码实现了上述提到的功能,其中包含了几个重要的部分: - 计算字符串哈希值的方法 `rabin_karp_hash()`, - 验证特定长度下是否存在回文的方法 `check_palindrome()`, - 结合二分查找逻辑寻找最长达标的回文子串的核心过程 `longest_palindromic_substring_with_rk_and_binary_search()`.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值