作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
给定字符串 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/
我是一名优秀的程序员,十分优秀!