leetcode1160. 拼写单词

迷南。 2023-07-16 03:55 138阅读 0赞

题目描述:

给你一份『词汇表』(字符串数组) 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表的思路,这里暂且不提。

  1. class Solution {
  2. public int countCharacters(String[] words, String chars) {
  3. int ans = 0, index;
  4. String bChars = chars; // 因为下面对chars更改所以提前备份
  5. boolean flag;
  6. for(int i = 0; i < words.length; i++){ // 遍历每一个单词
  7. flag = true;
  8. chars = bChars;
  9. for(int j = 0; j < words[i].length(); j++){ // 遍历单词每一个字符
  10. index = chars.indexOf(words[i].charAt(j)); // 查找单词字符位置
  11. if(index != -1){ // 单词字符存在,将chars中对应的字符删去
  12. chars = chars.substring(0, index) + chars.substring(index + 1);
  13. }else{ // 字符不存在直接跳出,相当于进行下一个单词的判断
  14. flag = false; // 保证不会进行ans加
  15. break;
  16. }
  17. }
  18. if(flag){
  19. ans += words[i].length();
  20. }
  21. }
  22. return ans;
  23. }
  24. }

发表评论

表情:
评论列表 (有 0 条评论,138人围观)

还没有评论,来说两句吧...

相关阅读

    相关 1160. 拼写单词

    给你一份『词汇表』(字符串数组) `words` 和一张『字母表』(字符串) `chars`。 假如你可以用 `chars` 中的『字母』(字符)拼写出 `words` 中的

    相关 leetcode1160. 拼写单词

    题目描述: 给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。 假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某