提问者:小点点

循环执行的差异


有谁能解释一下这两种代码在执行上的区别吗?

1)

  #include <iostream>
using namespace std;

int main() {
    // your code goes here
    string code;
    getline(cin,code);
    for(int i=0;i<code.length();i++){
        if(code[i]=='.'){
            code.replace(i,1,"[.]");
        }
    }
    cout<<code;
    return 0;
}

上述程序代码的输出屏幕显示“超过时限”。

Time limit exceeded #stdin #stdout 5s 5220KB
#include <iostream>
using namespace std;

int main() {
    // your code goes here
    string code;
    getline(cin,code);
    for(int i=0;i<code.length();i++){
        if(code[i]=='.'){
            code.replace(i,1,"[.]");
            i++;
        }
    }
    cout<<code;
    return 0;
}

而第2段代码显示了所需的输出。

1[.]1[.]1[.]1

有人能解释一下,在其中一个输出显示“tle”(迭代计数必须在for循环本身中声明),而另一个显示输出的情况下,执行是如何进行的吗?


共2个答案

匿名用户

我们可以这样做,看看会发生什么,例如,使用以下输入:

code = "google.com"

过一会儿,i将等于6,然后就发生了:

i          code
6          google[.]com     (and now there's a dot on place 7)
7          google[[.]]com   (and now there's a dot on place 8)
8          google[[[.]]]com (and now there's a dot on place 9)
...        ...

而且没有办法阻止这一切。

由于替换使点的位置向右移动了一个,因此在另一种意义上使用for循环可能是一个好主意:

for(int i=code.length()-1;i>=0;i--)

匿名用户

在此循环中:

for(int i=0;i<code.length();i++){
        if(code[i]=='.'){
            code.replace(i,1,"[.]");
        }
    }

当您替换[.]时,在循环的下一次迭代中,i现在是刚才插入的.的索引。 该.将再次被替换,以此类推,无限多次,导致“超过时限”。

在第二个版本中,当完成替换时,i被正确地移动到指向]。您也可以将它再移动一步,因为您知道在该位置也没有.