来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。
示例 1:
输入:words = [“cat”,“bt”,“hat”,“tree”], chars = “atach”
输出:6
解释:
可以形成字符串 “cat” 和 “hat”,所以答案是 3 + 3 = 6。
示例 2:
输入:words = [“hello”,“world”,“leetcode”], chars = “welldonehoneyr”
输出:10
解释:
可以形成字符串 “hello” 和 “world”,所以答案是 5 + 5 = 10。
提示:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
所有字符串中都仅包含小写英文字母
常规解法(效率低)
class Solution {
public int countCharacters(String[] words, String chars) {
int count = 0;
List<Character> charList = new ArrayList<Character>();
char[] allChars = chars.toCharArray();
for (int i = 0; i < words.length; i++) {
String word = words[i];
int tempCount = 0;
charList.clear();
for (char ch : allChars) {
charList.add(ch);
}
for (int j = 0; j < word.length(); j++) {
char temp = word.charAt(j);
if (charList.contains(temp)) {
tempCount++;
charList.remove((Character) temp);
} else {
tempCount = 0;
break;
}
}
count += tempCount;
}
return count;
}
}
拆分字符串为数组
class Solution {
public int countCharacters(String[] words, String chars) {
int lengths = 0;
int cnt = 0;
char[] alphbet = chars.toCharArray();
int [] count = new int[100];
boolean[] isClear = new boolean[1001];
for(char charItem:alphbet){
count[charItem-97]++;
}
for(String item:words){
int[] countCopy = Arrays.copyOf(count,count.length);
char[] tmp = item.toCharArray();
for(char tmpItem:tmp){
if(countCopy[tmpItem-97]==0){
isClear[cnt]=false;
break;
}else{
countCopy[tmpItem-97]--;
isClear[cnt]=true;
}
}
cnt++;
}
for(int i=0;i<isClear.length;i++){
if(isClear[i]){
lengths+=words[i].length();
}
}
return lengths;
}
}
HashMap
class Solution
{
public int countCharacters(String[] words, String chars)
{
if(words.length==0||chars.length()==0)return 0;
char[] ch=chars.toCharArray();
HashMap<Character,Integer> map=new HashMap<>();
int ans=0;
for(char c:ch)
{
map.put(c,map.getOrDefault(c,0)+1);
}
int len=words.length;
for(int i=0;i<=len-1;i++)
{
boolean flag=false;
char[] cc=words[i].toCharArray();
HashMap<Character,Integer> temp=(HashMap)map.clone();
for(int j=0;j<=cc.length-1;j++)
{
if(!map.containsKey(cc[j])){flag=true;break;}//no such,break
else
{
if(temp.get(cc[j])>=1)temp.put(cc[j],temp.get(cc[j])-1);//enough,then -1
else {flag=true;break;}//not enough,break
}
}
if(flag)continue;
ans+=words[i].length();
}
return ans;
}
}