import java.util.HashMap;
/**
* @auther 飞行员夹克儿
* @create 2021-11-01-21:30
*
*
*给定一字符集合 a 和 一字符串集合 b;用集合 a 里的字符
* 匹配集合 b 中的字符串,求成功匹配的字符串总长度;
*
*其中 a 匹配 b 中一个字符串时,a 中字符不能重复使用;
* 但在匹配下一个字符串时,可重复使用;
*
* 输入
* 字符集合a : {‘1’,‘2’,‘3’,‘4’,‘4’}
* 字符串集合b:{‘123’,‘344’,‘112’,‘345’}
* 输出
* 集合b中字符串中,能与a匹配的有 123 与 344;顾输出总长度 6
* 其中
* 112不匹配是因为集合a中只有1个’1’
* 345不匹配是因为集合a中没有
*
*
*/
public class Main1 {
public static void main(String[] args) {
char[] s1 = {'w','o','r','k','s'};
String[] strings = {"work","wkor","works","woks"};
HashMap<Character,Integer> map1 = new HashMap();
for (char s: s1) {
if (map1.get(s)==null){
map1.put(s,1);
}else{
map1.put(s,(Integer)map1.get(s)+1);
}
}
//System.out.println(map1);
int count = 0;
boolean b = true;
for (String s:strings) {
HashMap<Character,Integer> map2 = new HashMap();
char[] chars = s.toCharArray();
for (char c: chars) {
if (map2.get(c)==null){
map2.put(c,1);
}else{
map2.put(c,(Integer)map2.get(c)+1);
}
}
//System.out.println(map2);
for (char c:map2.keySet()) {
if ((map1.get(c)== null ? 0 : map1.get(c)) < map2.get(c)){
b = false;
}
}
if (b){
count += s.length();
}
b = true;
}
System.out.println(count);
}
}
//使用getOrDefault优化
public class Main1 {
public static void main(String[] args) {
char[] s1 = {'w','o','r','k','s'};
String[] strings = {"work","wkor","works","woks"};
HashMap<Character,Integer> map1 = new HashMap();
for (char s: s1) {
map1.put(s,map1.getOrDefault(s,0)+1);
}
//System.out.println(map1);
//
int count = 0;
boolean b = true;
for (String s:strings) {
HashMap<Character,Integer> map2 = new HashMap();
char[] chars = s.toCharArray();
for (char c: chars) {
map2.put(c,map2.getOrDefault(c, 0)+1);
}
//System.out.println(map2);
for (char c:map2.keySet()) {
if (map1.getOrDefault(c,0) < map2.get(c)){
b = false;
}
}
if (b){
count += s.length();
}
b = true;
}
System.out.println(count);
}
}
Map 的 getOrDefault( )