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' to
int[][]' 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/