c# - 在确定一个字符串需要多少个字母替换为另一个字符串的变位词时,我的算法有什么缺陷?

标签 c# algorithm

我已经盯着这个看了半个小时了,我不知道我哪里错了!在某些测试用例中,我得到的 count 答案显然不正确。我已经测试了该程序的每个子例程并且它按预期工作。那么 WTF?

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) // str couldn't be split into halves
            {
                Console.WriteLine(-1);
                continue;
            }
            // determine how many replacements s1 needs to be an anagram of s2
            int n = str.Length / 2;
            string s1 = str.Substring(0, n);
            string s2 = str.Substring(n, n);
            int[,] counter = new int[26,2]; // counter[i,j] will be the # of occurences of the i-th letter
                                            // of the alphabet in string sj
            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;
            }

            // sum difference of occurences in each letter, and divide sum by 2
            int count = 0;
            for(int i = 0; i < n; ++i)
            {
                count += Math.Abs(counter[i, 0] - counter[i, 1]);
            }
            count /= 2; 

            Console.WriteLine(count);
        }
    }
}

测试输入:

aaabbb
ab
abc
mnop
xyyx
xaxbbbxx

我的输出:

3
0
-1
0
0
1

预期输出:

3
1
-1
2
0
1

最佳答案

s2 被分配为:

string s2 = str.Substring(n, n);

我猜你想使用:

string s2 = str.Substring(n, str.Length);

我认为这应该可以解决您遇到的问题,但是对于第一个输入,您当前的输出异常准确

关于c# - 在确定一个字符串需要多少个字母替换为另一个字符串的变位词时,我的算法有什么缺陷?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38792223/

相关文章:

algorithm - 从前序和后序遍历中绘制树而不对树的形状做任何假设

c# - 在 C# 中捕获声音输出

c# - 从 byte[] 中删除尾随零?

c# - 将 DialogViewController 推送到 ViewController 到 NavigationController 堆栈上会产生 2 页

c# - 返回具有空值的类

algorithm - 为了理解算法分析书籍而需要学习的数学领域列表(例如算法简介)

c# - 如何在单击按钮时发送远程通知? Xamarin.Android C#

algorithm - 输入的微小变化总是会导致输出发生较大变化的函数

algorithm - 时间复杂度是 sqrt(n) 但我们如何获得它呢?

python - 存储动态数据频率的策略