【问题标题】:Why does this code output different results for the same inputs?为什么此代码为相同的输入输出不同的结果?
【发布时间】:2020-08-26 07:12:50
【问题描述】:

我编写了一个简单的程序来查找 C++ 中给定字符串中具有不同字符的最长子字符串。我的代码适用于某些输入,但不适用于其他输入。此外,它为相同的输入提供了不同的输出。我哪里错了?

int main() {
    int t;
    cin >>t;
    while(t--){
        string s;
        cin >> s;
        int n = s.length();
        int maxlen = 0;
        for(int i = 0; i < n; i++){
            int count = 0;
            int arr[26] = {0};
            bool isDist = true;
            int j = i;
            while(isDist){
                if(arr[(int)s[j] - (int)'a'] == 0){
                    count++;
                    arr[(int)s[j] - (int)'a'] = 1;
                    j++;
                } else {
                    isDist = false;
                } 
            }
            if(count > maxlen) maxlen = count;
        }
        cout << maxlen << endl;
    }
    return 0;
}

对于以下输入:

3
aewergrththy
aewergrththy
aewergrththy

我的代码输出:

5
4
4

感谢您的帮助,谢谢!

【问题讨论】:

    标签: c++ string substring


    【解决方案1】:

    问题是没有检查j 仍然小于n,因此您开始检查字符串末尾以外的字符,从而导致不可预测的结果。试试

    while (isDist && j < n)
    

    这应该会有所帮助,但我没有检查您的其余代码是否有错误。

    您也可以考虑使用s.at(j) 代替s[j]。这至少会在超出范围时产生可预测的行为,at 在这种情况下会引发异常。

    【讨论】:

      【解决方案2】:

      程序具有未定义的行为,因为您在使用j 迭代字符串时没有进行边界测试。除了isDist之外,您还应该修改内部循环以测试j

      while(isDist && j < n)
      

      如果没有这个,j 很容易在字符串中的所有剩余字符还没有遇到时就跳过字符串的末尾。

      在这种情况下,它将在您处理字符串末尾的字符'y' 时。处理完'y' 后,您将推进j 以使s[j] 返回字符串终止符。现在,您将使用 arr[0 - 'y'] 访问数组,这当然是由于是负索引而未定义的行为。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-16
        • 2013-10-25
        • 1970-01-01
        • 1970-01-01
        • 2019-10-07
        • 1970-01-01
        • 2017-01-03
        • 1970-01-01
        相关资源
        最近更新 更多