Leetcode 2020春招必刷61题-12
题目:拼写单词
给你一份『词汇表』(字符串数组) 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
所有字符串中都仅包含小写英文字母
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
起初看到这个题目,我的思路是利用一个for循环把词汇表中每一个字符串的每一个字符与字母表的每一个字符单独进行对比,如果相同则替换成空字符串,如果替换完成后词汇表有空的字符串,我们则认为掌握了这个单词,把这个单词替换前的长度进行记录,这个方法可能比较笨,但是我目前只想到这一种方法。说的可能比较绕,看一哈代码就懂了。
代码:
class Solution {
public int countCharacters(String[] words, String chars) {
int count = 0;
for(String s : words){
int length = s.length();
for(int i=0; i<chars.length(); i++){
String temp = String.valueOf(chars.charAt(i));
s = s.replaceFirst(temp,"");
}
if(s.length() == 0) count += length;
}
return count;
}
}
完事儿我又看了哈题解区大佬的思路,真的是被虐的体无完肤。在这里贴一下大佬的思路:
对于这道题,用数组c来保存字母表里每个字母出现的次数
如法炮制,再对词汇表中的每个词汇都做一数组w,比较数组w与数组c的对应位置
如果w中的都不大于c,就说明该词可以被拼写出,长度计入结果
如果w其中有一个超过了c,则说明不可以被拼写,直接跳至下一个(这里用到了带label的continue语法)
class Solution {
public int countCharacters(String[] words, String chars) {
int[] c = new int[26];
for(char cc : chars.toCharArray()) {
c[(int)(cc - 'a')] += 1;
}
int res = 0;
a: for(String word : words) {
int[] w = new int[26];
for(char ww : word.toCharArray()) {
w[(int)(ww - 'a')] += 1;
}
for(int i=0; i<26; i++) {
if(w[i] > c[i]) {
continue a;
}
}
res += word.length();
}
return res;
}
}
作者:pendygg