题解 | #牛群构成判断#
牛群构成判断
https://www.nowcoder.com/practice/b7b8c4d6390146dabe52d78e9e7136c6
知识点
字符串,哈希
解题思路
这道题的意思是比较s和t两个字符串中各字符数量是否相同。
使用两个map来分别存放两个字符串字符对应的数量,比较这两个map,如果出现某个字符数量不等返回false,遍历完map就可以返回true。
Java题解
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param t string字符串 * @return bool布尔型 */ public boolean areHerdCompositionsEqual (String s, String t) { // write code here HashMap<Character,Integer> map1=new HashMap<>(); for(int i=0;i<t.length();i++){ char ch=t.charAt(i); map1.put(ch,map1.getOrDefault(ch,0)+1); } HashMap<Character,Integer> map2=new HashMap<>(); for(int i=0;i<s.length();i++){ char ch=s.charAt(i); map2.put(ch,map2.getOrDefault(ch,0)+1); } for(char ch:map1.keySet()){ if(map2.get(ch)==null||map2.get(ch)!=map1.get(ch)){ return false; } } return true; } }