今天起 遇到力扣上比较有意思的题就记录下来!
力扣1160:拼写单词
题目链接: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。
解题思路
遇到有提示字符串仅包含小写(或者大写)英文字母的题,
都可以试着考虑能不能构造长度为26的每个元素分别代表一个字母的数组,来简化计算
对于这道题,用数组alph来保存字母表里每个字母出现的次数
如法炮制,再对词汇表中的每个词汇都做一数组wordLi,比较数组wordLi与数组alph的对应位置
如果wordLi中的都不大于alph,就说明该词可以被拼写出,长度计入结果
如果wordLi其中有一个超过了alph,则说明不可以被拼写,直接跳至下一个(这里用到了带label的continue语法)
代码:
class Solution { public int countCharacters(String[] words, String chars) { int[] alph = new int[26]; for(char alphChar : chars.toCharArray()) { alph[(int)(alphChar - 'a')] += 1; } int totalLength = 0; a: for(String word : words) { int[] wordLi = new int[26]; for(char wordChar : word.toCharArray()) { wordLi[(int)(wordChar - 'a')] += 1; } for(int i=0; i<26; i++) { if(wordLi[i] > alph[i]) { continue a; } } totalLength += word.length(); } return totalLength; } }