力扣#1160 拼写单词
题目要求:给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。
输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释:
可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。
题目思路:首先必定是要对words数组进行遍历的,而且还需要两个for循环,第二个循环里面需要检查单词的字母是否在chars字符串里面出现,那么思路就可以在这里进行优化,爆破的思路就是再用一个循环判断字母是否出现在chars里面,这种复杂度就会太高。不如直接用一个哈希表储存chars里面的,这样查询的时候复杂度就可以是O(1)。
总的时间复杂度就会是O(n^2)
代码:
import java.util.HashMap;
public class HelloWorld {
private String[] words;
private String chars;
public static void main(String[] args) {
String[] words = {"cat","bt","hat","tree"};
String chars = "atach";
HashMap<String , Integer> kv = new HashMap<String, Integer>();
//char[] chars1 = chars.toCharArray();
for (int i = 0; i< chars.length(); ++i){
System.out.println(chars.substring(i,i+1));
if(kv.containsKey(chars.substring(i,i+1))){
kv.replace(chars.substring(i,i+1), kv.get(chars.substring(i,i+1))+1);
}
else{
kv.put(chars.substring(i,i+1), 1);
}
}
System.out.println(kv);
int sum = 0;
for(int i = 0; i< words.length; ++i){
HashMap<String , Integer> temp = new HashMap<String, Integer>();
temp.putAll(kv);
//System.out.println(temp);
boolean flag = false;
int j;
//String word = words[i];
for(j = 0; j<words[i].length(); ++j){
if((temp.containsKey(words[i].substring(j,j+1))) && (temp.get(words[i].substring(j,j+1)) != 0)){
//int n = temp
temp.replace(words[i].substring(j,j+1), temp.get(words[i].substring(j,j+1))-1);
flag = true;
}else{
flag = false;
break;
}
}
if(flag){
System.out.println(words[i]);
}
sum += flag?j:0;
}
System.out.println(sum);
}
}