题目:
分析
这道题主要需要做的是,对每个单词进行检查,我利用list的contains来进行判断,存在就删除掉这个字母,不存在则继续遍历
代码
class Solution {
public int countCharacters(String[] words, String chars) {
int res=0;
List<Character> ch=new ArrayList<>();
for(int i=0;i<chars.length();i++){
ch.add(chars.charAt(i));
}
for(int i=0;i<words.length;i++){
List<Character> temp=new ArrayList(ch);
int j;
for(j=0;j<words[i].length();j++){
if(temp.contains(words[i].charAt(j))){
temp.remove(temp.indexOf(words[i].charAt(j)));
}else{
break;
}
}
if(j==words[i].length())
res+=j;
}
return res;
}
}
结果
小结
这样的写法其实效率非常低,创建了很多个list,大量占用了内存和增加计算时间
我在题解中看到了一个非常巧妙的方法,用map的原理来做,将代码分享给大家
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
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/solution/ji-de-di-yi-ci-kan-bie-ren-yong-int26de-shi-hou-be/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。