算法笔记 -- 1684. 统计一致字符串的数目

111 阅读2分钟

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

一、题目描述:

1684. 统计一致字符串的数目 - 力扣(LeetCode)

给你一个由不同字符组成的字符串 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 <= 10^4
  • 1 <= allowed.length <= 26
  • 1 <= words[i].length <= 10
  • allowed 中的字符 互不相同 。
  • words[i] 和 allowed 只包含小写英文字母。

二、思路分析:

题目已说 words[i] 和 allowed 只包含小写英文字母,且allowed由不同字符组成的字符串,则可以利用长度为26的int类型数组。

记录allowed每个字母出现的次数

遍历words每个字符串,如果该字符串中的字母对于数组中的次数为0,则不是一致字符串。

三、AC 代码:

class Solution {
    public boolean get(int[] nums,String str){
        for (int j = 0;j < str.length();j++){
            if (nums[str.charAt(j) - 'a'] == 0)
                return false;
        }
        return true;
    }
    public int countConsistentStrings(String allowed, String[] words) {
        int count = 0;
        int[] chars = new int[26];
        for (int i = 0;i < allowed.length();i++){
            chars[allowed.charAt(i) - 'a']++;
        }

        for (int i = 0;i < words.length;i++){
            if (get(chars,words[i]))
                count++;
        }
        return count;
    }
}

四、参考:

【1684. 统计一致字符串的数目】题解:集合set - 统计一致字符串的数目 - 力扣(LeetCode)

【简单】【1684. 统计一致字符串的数目】c语言,按部就班一般解法,暴力解法 - 统计一致字符串的数目 - 力扣(LeetCode)