【LeetCode】 1160. Find Words That Can Be Formed by Characters 拼写单词(Easy)(JAVA)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【LeetCode】 1160. Find Words That Can Be Formed by Characters 拼写单词(Easy)(JAVA),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1853字,纯文字阅读大概需要3分钟。
内容图文
![【LeetCode】 1160. Find Words That Can Be Formed by Characters 拼写单词(Easy)(JAVA)](/upload/InfoBanner/zyjiaocheng/638/ea9a1bf2218d4a41bd7cd2f50b1ff4f2.jpg)
【LeetCode】 1160. Find Words That Can Be Formed by Characters 拼写单词(Easy)(JAVA)
题目地址: https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/
题目描述:
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.
Example 1:
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation:
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Example 2:
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation:
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
Note:
1. 1 <= words.length <= 1000
2. 1 <= words[i].length, chars.length?<= 100
3. All strings contain lowercase English letters only.
题目大意
给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。
解题方法
1、遍历记录下 chars 里面每个字母的个数
2、遍历每个单词的每个字母,确认是否在 chars 字母个数的范围内
class Solution {
public int countCharacters(String[] words, String chars) {
int[] count = new int[26];
for (int i = 0; i < chars.length(); i++) {
count[chars.charAt(i) - 'a']++;
}
int res = 0;
for (int i = 0; i < words.length; i++) {
int[] temp = count.clone();
int j = 0;
for (; j < words[i].length(); j++) {
int cur = words[i].charAt(j) - 'a';
temp[cur]--;
if (temp[cur] < 0) break;
}
if (j == words[i].length()) res += words[i].length();
}
return res;
}
}
执行用时 : 9 ms, 在所有 Java 提交中击败了 72.91% 的用户
内存消耗 : 42.1 MB, 在所有 Java 提交中击败了 5.08% 的用户
内容总结
以上是互联网集市为您收集整理的【LeetCode】 1160. Find Words That Can Be Formed by Characters 拼写单词(Easy)(JAVA)全部内容,希望文章能够帮你解决【LeetCode】 1160. Find Words That Can Be Formed by Characters 拼写单词(Easy)(JAVA)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。