无法理解此字谜问题解决方案背后的逻辑 [英] Can't understand the logic behind this anagram problem's solution

查看:75
本文介绍了无法理解此字谜问题解决方案背后的逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出两个字符串a和b,它们的长度可以相同或不同,确定进行a和b字谜所需的最小字符删除数。任何字符都可以从这两个字符串中删除。

Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and b anagrams. Any characters can be deleted from either of the strings.

这是我第一次为竞争性编程做准备,但对我来说,理解这两个for循环背后的逻辑非常困难。

This is my first time preparing for competitive programming and understanding the logic behind the two for loops is quite hard for me.

String str1 = s.next();               
String str2 = s.next();
char []c1 = str1.toCharArray();
char []c2 = str2.toCharArray();
int []cnt1 = new int[26];
int []cnt2 = new int[26];

int len1 = str1.length();
for (int i = 0; i < len1; i++) {
    cnt1[c1[i] - 97]++;
}

int len2 = str2.length();
for (int i = 0; i < len2; i++) {
    cnt2[c2[i] - 97]++;
}

int cnt = 0;
for (int i = 0; i < 26; i++) {
    cnt += Math.abs(cnt2[i] - cnt1[i]);
}

System.out.println(cnt);


推荐答案

此代码段遍历每个字符串并计算每个字母在其中出现的次数(并将计数器存储在数组中以提高性能)。

This snippet goes over each string and counts the number of occurrences each letter has in it (and store the counters in an array for better performance).

然后遍历两个计数器数组,每个字母减去两个字符串的计数器(绝对值)。区别在于应删除该字符的数量。这些差异相加,结果就是答案。

It then goes over the two arrays of counters, and for each letter subtracts the counters for both strings (in absolute value). The difference is the number of that character that should be removed. These differences are summed, and the result is the answer.

这篇关于无法理解此字谜问题解决方案背后的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆