当前位置:   article > 正文

Leetcode答题 --- 拼写单词_leetcode单词表拼接字符串

leetcode单词表拼接字符串

题目

给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。

假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。

注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。

返回词汇表 words 中你掌握的所有单词的 长度之和。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters

示例

输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释: 
可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
  • 1
  • 2
  • 3
  • 4

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters

思路

遍历词汇表,将每个词转换成数组,然后遍历该词的每个字符去和字母表做判断,且字母表不是任意取的,每个字母的个数与词汇表的词相同,所以不能只进行简单的indexOf判断或includes判断

实现

var countCharacters = function(words, chars) {
  let allWords = []
  words.forEach(str => {
    let tempChars = chars.split('')
    let curStrArr = str.split('')
    let canPush = false
    for (let i = 0; i < curStrArr.length; i++) {
      if (tempChars.includes(curStrArr[i])) {
        tempChars.splice(tempChars.indexOf(curStrArr[i]), 1)
        canPush = true
      } else {
        canPush = false
        break
      }
    }
    if (canPush) {
      allWords.push(str)
    }
  })
  return allWords.length ? allWords.reduce((length, cur) => length + cur.length, 0) : 0
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/705376
推荐阅读
相关标签
  

闽ICP备14008679号