可排列的最长公共子序列(Longest common subsequence with permutations allowed)

本文介绍了一种求解两个字符串的最长有序公共子序列的方法,通过计算字符频率并利用计数数组找到共有字符,最终输出按字母顺序排列的最长子序列。

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

原文地址:Longest common subsequence with permutations allowed

已知两个小写的字符串。找出这两个字符串排过序后的公共子序列,输出的结果必须是排过序的。

例子:

Input  :  str1 = "pink", str2 = "kite"
Output : "ik" 

字符串"ik"是最长的有序字符串,它的其中的一个排列是"ik",而且是"pink"的子序列。另外的一个排列是"ki",它是"kite"的子序列。

Input  : str1 = "working", str2 = "women"
Output : "now"

Input  : str1 = "geeks" , str2 = "cake"
Output : "ek"

Input  : str1 = "aaaa" , str2 = "baba"
Output : "aa"

这个问题的想法就是对两个字符串中的字符进行计数。

1、计算每个字符串中的字符出现的频率,并将它们分别存储在计数数组中,比如str1存储在count1[]中,str2存储在count2[]中。

2、现在我们已经对26个字母进行了计数。所以遍历count1[],对于任何一个下标‘i’用结果字符串连接字符‘result’连接min(count1[i], count2[i]) 次字符 (‘a’+i)。

3、因为我们是按照升序遍历的计数矩阵,所以我们最后的字符串中的字符也是排过序的。

// C++ program to find LCS with permutations allowed
#include<bits/stdc++.h>
using namespace std;

// Function to calculate longest string
// str1     --> first string
// str2     --> second string
// count1[]  --> hash array to calculate frequency
//              of characters in str1
// count[2]  --> hash array to calculate frequency
//              of characters in str2
// result   --> resultant longest string whose
// permutations are sub-sequence of given two strings
void longestString(string str1, string str2)
{
    int count1[26] = {0}, count2[26]= {0};

    // calculate frequency  of characters
    for (int i=0; i<str1.length(); i++)
        count1[str1[i]-'a']++;
    for (int i=0; i<str2.length(); i++)
        count2[str2[i]-'a']++;

    // Now traverse hash array
    string result;
    for (int i=0; i<26; i++)

        // append character ('a'+i) in resultant
        // string 'result' by min(count1[i],count2i])
        // times
        for (int j=1; j<=min(count1[i],count2[i]); j++)
            result.push_back('a' + i);

    cout << result;
}

// Driver program to run the case
int main()
{
    string str1 = "geeks", str2 = "cake";
    longestString(str1, str2);
    return 0;
}

输出:

ek

时间复杂度:O(m + n),在这里m和n分别是两个输入字符串的长度。
空间复杂度:O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值