给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
你可以按任意顺序返回答案。

示例

示例 1:
输入:[“bella”,”label”,”roller”]
输出:[“e”,”l”,”l”]
示例 2:

输入:[“cool”,”lock”,”cook”]
输出:[“c”,”o”]

解题

题目的意思就是取所有word里都有的字母

比如 “bella” 有 1个b 1个e 2个l 1个a
“label” 有 2个l 1个a 1个b 1个e
“roller” 有 1个r 1个o 2个l 1个e 1个r

这3个单词相交,得出都有 1个e 和 2个l

所以可以先把第一个单词拆解成一个个字母,记录字母个数,再遍历所有单词,与之对比字母个数,取交集。最后得出结果

  1. /**
  2. * @param {string[]} words
  3. * @return {string[]}
  4. */
  5. var commonChars = function(words) {
  6. const list = new Array(26).fill(0)
  7. for (let i = 0; i < words[0].length; i++) {
  8. list[words[0][i].charCodeAt() - 97]++
  9. }
  10. for (let i = 1; i < words.length; i++) {
  11. const arr = new Array(26).fill(0)
  12. for (let j = 0; j < words[i].length; j++) {
  13. arr[words[i][j].charCodeAt() - 97]++
  14. }
  15. for (let j = 0; j < 26; j++) {
  16. list[j] = Math.min(list[j], arr[j])
  17. }
  18. }
  19. const res = []
  20. for (let i = 0; i < list.length; i++) {
  21. if (list[i] > 0) {
  22. for (let j = 0; j < list[i]; j++) {
  23. res.push(String.fromCharCode(i + 97))
  24. }
  25. }
  26. }
  27. return res
  28. };

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-common-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。