给定字符串 S1 和字符串 S2。将字符串 S1 转换为回文字符串,例如 S2 是该回文字符串的子字符串。 S1 上允许的唯一操作是将任何字符替换为任何其他字符。找出所需的最少操作次数。
我已经编写了这段代码,可以计算需要使用常规字符串进行多少次更改才能将其转换为回文,但我不知道如何使其工作,可以说输入为string n = "aaaaa" and 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;
}
}
逻辑是将 s2 放置在 s1 中的每个位置并计算其成本。输出其中成本最小的。该算法的时间复杂度为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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)