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。
提示:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
所有字符串中都仅包含小写英文字母
思路:
当然是遍历每一个单词,每一个单词遍历每一个字符。将字符挨个与chars对比。这里我一开始没看清题,题目说每个字符不可重复利用,所以每对比完一个字符我就把这个字符删去。
有更好的hash表的思路,这里暂且不提。
class Solution {
public int countCharacters(String[] words, String chars) {
int ans = 0, index;
String bChars = chars; // 因为下面对chars更改所以提前备份
boolean flag;
for(int i = 0; i < words.length; i++){ // 遍历每一个单词
flag = true;
chars = bChars;
for(int j = 0; j < words[i].length(); j++){ // 遍历单词每一个字符
index = chars.indexOf(words[i].charAt(j)); // 查找单词字符位置
if(index != -1){ // 单词字符存在,将chars中对应的字符删去
chars = chars.substring(0, index) + chars.substring(index + 1);
}else{ // 字符不存在直接跳出,相当于进行下一个单词的判断
flag = false; // 保证不会进行ans加
break;
}
}
if(flag){
ans += words[i].length();
}
}
return ans;
}
}
还没有评论,来说两句吧...