LeetCode 每日 1 题:统计一致字符串的数目

67 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第 23 天,点击查看活动详情

统计一致字符串的数目

原题地址

给你一个由不同字符组成的字符串 allowed 和一个字符串数组 words 。如果一个字符串的每一个字符都在 allowed 中,就称这个字符串是 一致字符串

请你返回 words 数组中 一致字符串 的数目。

示例 1:

输入:allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
输出:2
解释:字符串 "aaab""baa" 都是一致字符串,因为它们只包含字符 'a''b'

示例 2:

输入:allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
输出:7
解释:所有字符串都是一致的。

示例 3:

输入:allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
输出:4
解释:字符串 "cc""acd""ac""d" 是一致字符串。

提示:

  • 1<=words.length<=1041 <= words.length <= 10^4
  • 1<=allowed.length<=261 <= allowed.length <= 26
  • 1 <= words[i].length <= 10
  • allowed 中的字符 互不相同 。
  • words[i] 和 allowed 只包含小写英文字母。

思路分析

  1. 根据题目对一致字符串的定义可以知道,如果一个字符串中的所有字符都在 allowed 里面,则可以认为这个字符串是一致字符串;
  2. 定义 isConsistent 来判断一个字符串是否为一致字符串,入参为 allowed 和 一个字符串 word,循环 word,使用 includes 方法判断word中的每个字符是否在 allowed 中,若有一个不在则返回 false,否则遍历结束后返回 true
  3. 然后遍历 words,分别判断 word是否是一致字符串,true 时,将 result 数值加一,最后返回 result

AC 代码

/**
 * @param {string} allowed
 * @param {string[]} words
 * @return {number}
 */
var countConsistentStrings = function(allowed, words) {
    let result = 0
    for(let i = 0; i < words.length; i++) {
        if(isConsistent(allowed, words[i])) {
            result += 1
        }
    }
    return result
};


var isConsistent = function (allowed, word) {
    for(let i = 0; i < word.length; i++) {
        if(!allowed.includes(word[i])) {
            return false
        }
    }
    return true
}

结果:

  • 执行结果: 通过
  • 执行用时:104 ms, 在所有 JavaScript 提交中击败了43.70%的用户
  • 内存消耗:49.8 MB, 在所有 JavaScript 提交中击败了72.64%的用户
  • 通过测试用例:74 / 74

END