为什么要从给定的字符串中减去字符值
Why is the character value gets subtracted from the given string
给出了 2 个不同的字符串,问题是从给定的字符串中找出最少的删除次数,使两个字符串都成为变位词。我在某个地方看到了这个代码片段,我所有的测试用例都通过了,但无法理解其中的逻辑。即,为什么要减'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
和 s2
是字符串。
当您调用 s1[i]
时,您正在访问 s1
的第 i 个字符,它也是一个 int
,表示该字符在 ASCII table.
例如,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;
给出了 2 个不同的字符串,问题是从给定的字符串中找出最少的删除次数,使两个字符串都成为变位词。我在某个地方看到了这个代码片段,我所有的测试用例都通过了,但无法理解其中的逻辑。即,为什么要减'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
和 s2
是字符串。
当您调用 s1[i]
时,您正在访问 s1
的第 i 个字符,它也是一个 int
,表示该字符在 ASCII table.
例如,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;