- LeetCode1160.拼写单词
给你一份『词汇表』(字符串数组) 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。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
- 分析:
首先将词汇表和字母表都转化为字符数组,然后遍历每个单词的字符数组,再遍历字母表字符数组,对比这两个字符数组,把字母表中与当前单词字母相同的字符#;然后统计个数;最终判断当前#的个数与单词字母的个数是否一致。如果相同则认为可以拼写出当前的单词,然后输出字母个数即可。
class Leetcode1160 {
public static void main(String[] args){
String[] words={"cat","bt","hat","tree"};
String chars="atach";
System.out.println("字母总个数:"+countCharacters(words,chars));
}
public static int countCharacters(String[] words, String chars) {
int res=0;
char[] ch=chars.toCharArray(); //将字符串转为字符数组
for(String len:words){ //遍历单词数组 将元素赋给len 字符串
int a=0;
char[] word=len.toCharArray(); //将字符串len 转为字符数组
for(int i=0;i<word.length;i++){ //遍历单词转化出的字符数组
for(int j=0;j<ch.length;j++){ //遍历所给的字母表
if(word[i]==ch[j]){ //如果当前单词的字母在字母表存在
ch[j]='#'; //字母表当前的字母变成“#”
a++; //计数
break;
}
}
}
ch=chars.toCharArray(); //一个单词遍历完之后 更新一下字母表
if(a==word.length){ //如果赋予“#”字母个数 等于 当前单词的个数
res+=a; //计入总数
}
}
return res;
}
}