c# - 如何定义一个 26x2 数组然后在其行上使用 LINQ?

标签 c# arrays algorithm linq data-structures

Grrrr 我有 C# 和多维数组。出于某种原因,来自 C/C++ 背景,他们真的让我很烦。

所以当我运行的时候

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{    
    static void Main(String[] args)
    {
        int T = Int32.Parse(Console.ReadLine());
        for(int t = 0; t < T; ++t)
        {
            string str = Console.ReadLine();
            if(str.Length % 2 == 1)
            {
                Console.WriteLine(-1);
                continue;
            }
            int n = str.Length / 2;
            // determine how many replacements s1 needs to be an anagram of s2
            string s1 = str.Substring(0, n);
            string s2 = str.Substring(n, n);
            int[][] counter = new int[26][2];
            int ascii_a = (int)'a';
            for(int i = 0; i < n; ++i)
            {
                counter[(int)s1[i] - ascii_a][0] += 1;
                counter[(int)s2[i] - ascii_a][1] += 1;
            }
            int count = counter.Select((pair => Math.Abs(pair[0] - pair[1]))).Sum();
            Console.WriteLine(count);
        }
    }
}

我明白了

solution.cs(22,42): error CS0029: Cannot implicitly convert type int' toint[][]' Compilation failed: 1 error(s), 0 warnings

不知道为什么。

我可以改成

        int[,] counter = new int[26,2];
        int ascii_a = (int)'a';
        for(int i = 0; i < n; ++i)
        {
            counter[(int)s1[i] - ascii_a, 0] += 1;
            counter[(int)s2[i] - ascii_a, 1] += 1;
        }
        int count = counter.Select((pair => Math.Abs(pair[0] - pair[1]))).Sum();

但是,当然,我的 LINQ 语句中断了。

最佳答案

如果你改变

        int[][] counter = new int[26][2];

        int[][] counter = new int[26][];
        for (int i = 0; i < counter.Length; i++)
            counter[i] = new int[2];

代码编译。您可以根据需要测试其余部分。因为您没有在 OP 中提供必要的输入。

关于c# - 如何定义一个 26x2 数组然后在其行上使用 LINQ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38791386/

相关文章:

c# - 设计器显示 A 'Binding' can only be set on a DependencyProperty of a DependencyObject 错误

c# - 从位数组更改为枚举

ios - 用另一个字典替换数组中的字典

algorithm - 排序数组交集的修改

Python Puzzle 代码审查(剧透)

c# - 程序集中的所有 NUnit 测试都会被跳过,因为我在引用的项目中添加了空参数检查

c# - 类库允许使用未分配的结构

c++ - 指向数组转换的指针

Javascript:如何创建多维数组?

algorithm - 如何迭代生成 de Bruijn 序列?