将 S1 转换为回文,并将 S2 作为其子字符串



https://discuss.codechef.com/t/given-string-s1-and-s2-how-to-convert-given-string-s1-with-minimum-changes-to-palindrome-which-includes-s2-as-substring/69769

有人可以帮助我理解这段代码吗

#include<bits/stdc++.h>

使用命名空间标准;

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]) //(explain please) 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)) // (explain please)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;

}

回文...向后和向前相同... 代码的第一部分将 s2 覆盖在 s1 中的字符之上,从某个位置开始:i。 字符串 temp 是 S1 的第一个 i 字符,然后是 S2 的所有字符,然后是 S1 中未覆盖的任何字符。 温度的长度应为 s1 的长度。

在 j 循环中,您正在迭代 0 到 s1 舍入大小的一半。

您的第一个"请解释"是查看字符串 temp 中的索引 j 是否落在属于 s1 的字符上(无论是在 s2 字符之前还是之后(。 它还查看索引 j 处 temp 中的字符是否与其在另一侧的位置匹配(即该字符及其镜像是否已经相等,因为它们必须在回文中(。 如果 是 s1 的一部分,但不是匹配项,则需要付费。

你的第二个"请解释"看着临时字符串的后半部分......它查看字符串 temp 中 j 镜像位置处的字符是否落在属于 S1 的字符上,并再次查看该位置的字符是否与其翻转匹配......如果没有,则需要付出代价。

您基本上是在查看临时字符串中的字符,从字符串的末尾开始,然后向中间工作。 所以你先看第一个字符。 如果字符来自 s1,则可以将其切换为最后一个字符。所以你只是增加成本。 然后你看临时的最后一个字符。 如果它来自 s1,则可以将其切换为第一个字符。所以你只是增加成本。 现在递增 j,所以你正在查看第 2 个字符和第 2 个字符到最后一个字符,再次增加 j,您正在查看第 3 个字符和第 3 个字符到最后一个字符等等......

如果在任何时候你不能交换前面的字符,也不能交换后面的字符......那么如果它们还没有匹配,就不可能有一个回文。

相关内容

最新更新