【问题标题】:Why is the character value gets subtracted from the given string为什么从给定的字符串中减去字符值
【发布时间】:2020-10-05 04:20:25
【问题描述】:

给出了 2 个不同的字符串,问题是找出从给定字符串中删除的最小数量,以使两个字符串都成为字谜。我来看看这段代码 sn -p 一些地方和我所有的测试用例都通过了,但无法理解逻辑。也就是说,为什么要减去'a'?以及它的结果是什么。如果有人向我解释代码,那将非常有帮助。提前致谢。

int[] array=new int[26];
        for(int i=0;i<s1.Length;i++)
            array[s1[i]-'a']++;
        for(int i=0;i<s2.Length;i++)
            array[s2[i]-'a']--;
            int sum = 0;
        for(int i=0;i<26;i++)
        sum+=Math.Abs(array[i]);
        return sum;

【问题讨论】:

  • 在调试器中运行此代码并查看s1[i]'a' 的值。如果您希望我们提供帮助,您需要向我们展示 s1s2 是什么。
  • 请注意,此代码仅在字符串中的所有字符都是小写的假设下才有效。

标签: arrays string algorithm ascii absolute-value


【解决方案1】:

s1s2 是字符串。

当您调用s1[i] 时,您正在访问s1 的第i 个字符,这也是一个int,表示该字符在ASCII 表中的位置。

例如,a 是 ASCII 中的第 97 个字符。

当你做s1[i] - 'a'时,你基本上是在做s1[i] - 97

如果s1[i]a,那么s1[i] - 'a' 将为0。这将便于将字符从a 转换为z,用于从0 到25 的整数并将它们放入一个数组中。


代码分析

//create new array to represent the count for each character from 'a' to 'z'
int[] array = new int[26];

//count the caracters from s1. If there is 'a', add 1 to array[0], 
//if there is 'b', add 1 to array[1], ..., if there is 'z', add 1 to array[25].
for(int i = 0; i < s1.Length; i++) array[s1[i] - 'a']++;

//do the same thing, but subtracting. If there is 'a', subtract 1 from array[0], etc.
for(int i = 0; i < s2.Length; i++) array[s2[i] - 'a']--;

int sum = 0;

//for each letter, the absolute value of the matrix slot will say
//the positive difference between the 2 strings, so you know that
//if Math.Abs(array[0]) = 2, you need to remove 2 'a' from the strings.
for(int i = 0; i < 26; i++) sum += Math.Abs(array[i]);

return sum;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    相关资源
    最近更新 更多