class Solution {
public int countCharacters(String[] words, String chars){
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(int i = 0; i < chars.length(); i++){
char c = chars.charAt(i);
if(!map.containsKey(c)){
map.put(c, 1);
}else{
Integer count = map.get(c);
map.put(c, ++count);
}
}
int ans = 0;
for(String word : words){
HashMap<Character, Integer> map_clone = (HashMap<Character, Integer>) map.clone();
for(int i = 0; i < word.length(); i++){
if(!map_clone.containsKey(word.charAt(i))){ // 不包含该字符
break;
}else{
int num = map_clone.get(word.charAt(i));
if(num == 0){
break;
}else{
map_clone.put(word.charAt(i), --num);
}
}
if(i == word.length()-1){
ans += word.length();
}
}
}
return ans;
}
}
本地测试
package leetcode;
import java.net.Inet4Address;
import java.util.HashMap;
import org.openjdk.jol.vm.VM;
public class lc_1160_countCharacters {
public static void main(String[] args) {
String[] words = {"cat","bt","hat","tree"};
String chars = "atach";
// String[] words = {"hello","world","leetcode"};
// String chars = "welldonehoneyr";
lc_1160_countCharacters obj = new lc_1160_countCharacters();
int ans = obj.countCharacters(words, chars);
System.out.println(ans);
}
public int countCharacters(String[] words, String chars){
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(int i = 0; i < chars.length(); i++){
char c = chars.charAt(i);
if(!map.containsKey(c)){
map.put(c, 1);
}else{
Integer count = map.get(c);
map.put(c, ++count);
}
}
int ans = 0;
for(String word : words){
// HashMap<Character, Integer> map_clone = new HashMap<Character, Integer>(); // 也可以,map_clone和map内存地址不共享
HashMap<Character, Integer> map_clone = (HashMap<Character, Integer>) map.clone(); //map_clone和map内存地址不共享
// 注意不能写 HashMap<Character, Integer> map_clone = map,此时,map_clone和map共享一块内存地址
// System.out.println(VM.current().addressOf(map));
// System.out.println(VM.current().addressOf(map_clone));
// System.out.println(map.equals(map_clone));
for(int i = 0; i < word.length(); i++){
if(!map_clone.containsKey(word.charAt(i))){ // 不包含该字符
break;
}else{
int num = map_clone.get(word.charAt(i));
if(num == 0){
break;
}else{
map_clone.put(word.charAt(i), --num);
}
}
if(i == word.length()-1){
ans += word.length();
}
}
}
return ans;
}
}
注意
内存地址共享问题,详见代码注释
好文推荐:Java中equals与“==”的区别详解