【发布时间】:2020-10-28 21:27:29
【问题描述】:
我需要这个解决方案来解决 LeetCode 问题 1002:查找常用字符,但我没有找到合适的解决方案。
我需要的操作是用“a”和“b”之间的相交键更新映射“a”,并将键的值设置为两者中较低的值。
虽然这个用例很少,但有一个解决方案还是不错的。
class Solution {
public List<String> commonChars(String[] A) {
List<String> list = new ArrayList<>();
Map<Character, Integer> a = new HashMap<>();
Map<Character, Integer> b = new HashMap<>();
List<Character> removeChars = new ArrayList<>();
//base: populate map a so you can compare with next string in A[]
for(char c : A[0].toCharArray()){
int count = a.getOrDefault(c, 0);
a.put(c, count+1);
}
/*
compare each character in A[] to keys in map a
if contains
put character in map b and incremnt count
else
remove from map a
update map a with whatever has smaller value for each key
clear map b
iterate
put all keys in list for how many values it has
*/
for(int i = 1; i < A.length; i++){
for(char c : A[i].toCharArray()){
if(a.containsKey(c)){
int count = b.getOrDefault(c, 0);
b.put(c, count+1);
} else
a.remove(c);
}
/*
Here I need to compare the keys to each map
- If they were present in both, take the lower value
- If not, then I needed to remove the key from map "a"
*/
for(char c : removeChars){
a.remove(c);
}
b.clear();
}
for(Map.Entry<Character, Integer> entry : a.entrySet()){
char key = entry.getKey();
int val = entry.getValue();
for(int i = 0; i < val; i++){
list.add(String.valueOf(key));
}
}
return list;
}
}
【问题讨论】: