gpt4 book ai didi

c++ - 将给定字符串转换为具有给定子字符串的回文

转载 作者:太空狗 更新时间:2023-10-29 22:54:36 27 4
gpt4 key购买 nike

给定字符串 S1 和字符串 S2。将字符串 S1 转换为回文字符串,例如 S2 是该回文字符串的子字符串。 S1 上唯一允许的操作是用任何其他字符替换任何字符。查找所需的最少操作数。

我写了这段代码,它可以计算需要用常规字符串完成多少更改才能进入回文,但我不知道如何让它工作让输入为 string n = "aaaaa"and string (substring) m = "bbb" 并且输出必须是 3,因为需要三个更改才能使字符串 abbba in这种情况

这是我的代码

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string n = "aaaaa";
string m = "bbb";

if (n.size() <= m.size())
{
cnt = -1
}

if (n.size() > m.size())
{
string x, y;

int cnt=0;

if(n.size()%2!=0)
{
x=n.substr(0,n.size()/2);
y=n.substr(n.size()/2+1);
reverse(y.begin(),y.end());
}
else if(n.size()%2==0)
{
x=n.substr(0,n.size()/2);
y=n.substr(n.size()/2);
reverse(y.begin(),y.end());
}
for(int i=0;i<n.size();i++)
if(x[i]!=y[i])
cnt++;
cout<<cnt<<endl;
}

}

最佳答案

逻辑是将s2放在s1中的每一个位置,并计算s2的cost。输出其中成本最低的。该算法的时间复杂度为O(n^2)。

#include<bits/stdc++.h>
using namespace std;

int main(){

string s1,s2;
cin>>s1>>s2;
int l1=s1.length(),l2=s2.length();
int ans=INT_MAX;
if(l2>l1){

cout<<-1<<endl; // not possible
return 0;
}
for(int i=0 ; i<l1-l2+1 ; i++){

string temp=s1.substr(0,i)+s2+s1.substr(i+l2); // place s2 in all possible positions in s1
int cost=0;
// calculate cost to place s2
for(int j=i ; j<i+l2 ; j++){

if(s1[j]!=temp[j])
cost++;
}
int z=0;
// find the cost to convert new string to palindrome
for(int j=0 ; j<ceil(l1/2.0) ; j++){

if((j<i || j>=i+l2) && temp[j]!=temp[l1-j-1]) // if s2 is in the first half of new string
cost++;
else if(temp[j]!=temp[l1-j-1] && (l1-j-1<i || l1-j-1>=i+l2)) // if s2 is in the second half of new string
cost++;
else if(temp[j]!=temp[l1-j-1]){ // if s2 is in both halves

z=1;
break;
}
}
if(z==0)
ans=min(ans,cost);
}
if(ans==INT_MAX)
cout<<-1<<endl;
else
cout<<ans<<endl;
return 0;
}

关于c++ - 将给定字符串转换为具有给定子字符串的回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959424/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com