gpt4 book ai didi

c++ - 如何最好地遵循一个函数来理解它在做什么?

转载 作者:太空狗 更新时间:2023-10-29 19:59:55 24 4
gpt4 key购买 nike

这个问题很笼统,但我要举一个具体的例子。

需要解决的具体问题说明here .描述很长,所以我不会剪切和粘贴,但基本思想是输入字符串 S 和 T(在下面的代码中称为它们),找到需要对 S 进行的最少更改以生成 T。一个变化可以是:

  • 在字符串的任意一端插入一个字母。
  • 从字符串的任意一端删除一个字母。
  • 将一个字母更改为任何其他字母。

下面是我正在尝试跟踪的解决方案。我正在寻找的是有关如何最好地理解解决方案的提示。我可以使用哪些方法来阅读和理解代码(让我们放弃单步调试调试器)。

#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
char S[2010];
char T[2010];
int lens,lent;
int main()
{
int i,j,ma,p;

while(scanf("%s%s",S,T)!=EOF)
{
lens=strlen(S);
lent=strlen(T);
ma=0;p=0;
for(i=0;i<lens;i++)
{
p=0;
for(j=0;j<lent;j++)
{
if(i+j>=lens)
break;
if(S[i+j]==T[j]){p++;}
}
if(ma<p)
ma=p;
if(ma==lent)
break;
}
for(i=0;i<lent;i++)
{
p=0;
for(j=0;j<lens;j++)
{
if(i+j>=lent)
break;
if(T[i+j]==S[j]){p++;}
}
if(ma<p)
ma=p;
if(ma==lent)
break;
}
printf("%d\n",lent-ma);
}
return 0;
}

最佳答案

第 1 步:向自己解释变量代表什么:

S:我们要从中提取子串的字符串

T:以尽可能少的操作对提取的子串进行修改后,我们最终想要得到的字符串

lens:字符串S的长度

lent:字符串T的长度

i:提取子串开始的S中的索引

j:我们要匹配子串中相应字符的字符在字符串T中的索引

p:为当前调查的子串找到的匹配字符数

ma :任何子字符串的最大匹配字符数


第 2 步:确定了这些含义后,将第一个循环翻译成单词就相当简单了:

for loop 1 :    selects a start position of the substring

set the match counter to 0, since we start investigation of a new substring


for loop 2 : loops through the substring

if 1 : if there is no char left to read string S, stop looping

if 2 : if the current character in the extracted substring matches
a character in the "goal" string, increment the match counter (p)


if 3 : now, we finished looping through a substring,
if the count of matching characters in the substring and the goal
string was higher than for any of the previous counts,
then store this value as the max count

if 4 : if the max count of matching characters is equal to the
length of the "goal string", dr Moriatry can receive the goal string
with 0 substring changes, and hence, we can stop looping

下一个循环类似。 S 和 T 的角色有点颠倒了。但请注意,S 和 T 的角色并没有完全颠倒(正如某些人所说)。在这两种情况下,外部 for 循环的结束条件都使用 T 的长度,这是有道理的。

这里我们从字符串 T(“目标”字符串)中提取子字符串,并尝试将它们与字符串 S 进行匹配。我们为什么要这样做?

我希望编写代码的人能够解释以下情况,例如:

S = "b"     T = "abc"

如果我们只从 S 中提取子字符串并将它们与整个 T 字符串匹配,从第一个索引开始(就像第一个循环所做的那样),我们将只比较 "does b (在 S 中)匹配 a(T 中的第一个字符)然后我们继续说:“因为没有子串匹配,我们需要 3 个字符串更改操作来接收字符串 T”(这显然是错了,因为我们可以通过选择“b”作为要提取的子字符串,并进行 2 次更改操作以以 T 结尾来实现它)

关于c++ - 如何最好地遵循一个函数来理解它在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9944524/

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