C++ 将给定字符串转换为具有给定子字符串的回文
给定一个字符串S1和字符串S2。将字符串S1转换为回文字符串,例如S2是该回文字符串的子字符串。S1上唯一允许的操作是用任何其他字符替换任何字符。查找所需的最小操作数 我已经写了这段代码,它可以计算需要对正则字符串进行多少更改才能转换为回文,但我不知道如何使它工作,比如输入为C++ 将给定字符串转换为具有给定子字符串的回文,c++,string,C++,String,给定一个字符串S1和字符串S2。将字符串S1转换为回文字符串,例如S2是该回文字符串的子字符串。S1上唯一允许的操作是用任何其他字符替换任何字符。查找所需的最小操作数 我已经写了这段代码,它可以计算需要对正则字符串进行多少更改才能转换为回文,但我不知道如何使它工作,比如输入为string n=“aaaaaaa”和string(substring)m=“bbb”,输出必须是3,因为在本例中,需要进行三个更改才能使字符串abbba 这是我的密码 #include<iostream> #i
string n=“aaaaaaa”和string(substring)m=“bbb”
,输出必须是3
,因为在本例中,需要进行三个更改才能使字符串abbba
这是我的密码
#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;
}
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串n=“aaaaa”;
字符串m=“bbb”;
如果(n.size()m.size())
{
字符串x,y;
int-cnt=0;
如果(n.size()%2!=0)
{
x=n.substr(0,n.size()/2);
y=n.substr(n.size()/2+1);
反向(y.开始(),y.结束());
}
else if(n.size()%2==0)
{
x=n.substr(0,n.size()/2);
y=n.substr(n.size()/2);
反向(y.开始(),y.结束());
}
对于(int i=0;i逻辑是将s2放置在s1中的每个位置,并计算相同位置的成本。输出其中的最小成本。该算法的时间复杂度为O(n^2)
#包括
使用名称空间std;
int main(){
字符串s1、s2;
cin>>s1>>s2;
int l1=s1.length(),l2=s2.length();
int ans=int_MAX;
如果(l2>l1){
如果S2=“aba”,你会怎么做?你的算法会正确地推断出只需要一次替换吗?S[2]=“b”?@JohnMurray我没有预见到一切,因为目前我想不出更好的算法。这就是为什么我问是否有人可以用简单的示例更新我的代码推荐阅读:
#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;
}