追加和删除

时间:2019-09-12 17:54:05

标签: c#

解决Hackerrank问题并获得错误索引。

这是C#编码。问题说明可在此处https://www.hackerrank.com/challenges/append-and-delete/problem

中找到
class Solution {
    // Complete the appendAndDelete function below.
    static string appendAndDelete(string s, string t, int k) {
        int counter = 0;
        int n = s.Length;
        int m = t.Length;
        for(int i = 0; i <= Math.Min(n,m); i++)
        {
            if (s[i] == t[i])
            {
                counter++;
            }
            else
            {
                break;
            }

        }
        int a = n - counter;
        int b = m - counter;
        if (a + b <= k){
            return "Yes";
        }
        else{
            return "No";
        }
    }

执行时出现此错误

  

[错误]致命异常:System.IndexOutOfRangeException:索引超出数组的范围。       在solution.cs:24中的Solution.appendAndDelete(System.String s,System.String t,System.Int32 k)[0x0001b]处       在solution.cs:53中的Solution.Main(System.String [] args)[0x0002c]中

索引似乎在此范围内。

3 个答案:

答案 0 :(得分:2)

问题是您正在使用<=将迭代器与最小数组的Length属性进行比较。但是由于c#中的集合是基于0的,因此您尝试访问的索引不存在(最后一个索引始终为Length - 1)。

相反,请使用<运算符:

for (int i = 0; i < Math.Min(n, m); i++)
{
}

此外,从性能的角度来看,如果函数的返回值从不改变,则在每次迭代中调用函数通常不是一个好主意。相反,您应该先保存Math.Min()的值,然后执行循环:

var smallestLength = Math.Min(n, m); 

for (int i = 0; i < smallestLength; i++)
{
}

答案 1 :(得分:1)

您已经离开1。

 for(int i = 0; i < Math.Min(n,m); i++)

a b c

1 2 3

长度为3

但最后一个索引是:2

a b c

0 1 2

答案 2 :(得分:1)

<=应该是<

例如,长度为9的字符串的最大索引为8