1684. 统计一致字符串的数目(java / c / c++ / python / go / rust)

150 阅读1分钟

「这是我参与2022首次更文挑战的第9天,活动详情查看:2022首次更文挑战」。


1684. 统计一致字符串的数目:

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

分析

  • 面对这道算法题目,我陷入了沉思。
  • 遍历words是必然的,遍历每个单词的每个字符也是必然的。
  • 如何快速判断每个单词的每个字符都在allowed中是重点。
  • 每个字符都去遍历一遍allowed是最直观的想法,很显然效率太低。
  • 进一步考虑,使用hash表是可以的,明显要比遍历allowed效率高。
  • 由于字符的范围很明确,只包含小写英文字母,可以进一步使用数组代替hash表,效率会更高,有可能会浪费一些内存,但是微乎其微。

题解

java

class Solution {
    public int countConsistentStrings(String allowed, String[] words) {
        int ans = words.length;

        boolean[] flag = new boolean[128];
        for (int i = 0; i < allowed.length(); ++i) {
            flag[allowed.charAt(i)] = true;
        }
        
        for (String word : words) {
            for (int i = 0; i < word.length(); ++i) {
                if (!flag[word.charAt(i)]) {
                    --ans;
                    break;
                }
            }
        }

        return ans;
    }
}

c

int countConsistentStrings(char * allowed, char ** words, int wordsSize){
    int ans = wordsSize;

    bool flag[128] = {false};
    while (*allowed) {
        flag[*allowed] = true;
        ++allowed;
    }

    for (int i = 0; i < wordsSize; ++i) {
        char *word = words[i];
        while (*word) {
            if (!flag[*word]) {
                --ans;
                break;
            }
            ++word;
        }
    }

    return ans;
}

c++

class Solution {
public:
    int countConsistentStrings(string allowed, vector<string>& words) {
        int ans = words.size();

        bool flag[128] = {false};
        for (int i = 0; i < allowed.size(); ++i) {
            flag[allowed[i]] = true;
        }

        for (string &word: words) {
            for (int i = 0; i < word.size(); ++i) {
                if (!flag[word[i]]) {
                    --ans;
                    break;
                }
            }
        }

        return ans;
    }
};

python

class Solution:
    def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
        ans = len(words)
        flag = [False] * 128
        for c in allowed:
            flag[ord(c)] = True
        for word in words:
            for c in word:
                if not flag[ord(c)]:
                    ans -= 1
                    break
        return ans
        

go

func countConsistentStrings(allowed string, words []string) int {
    ans := len(words)

	flag := make([]bool, 128)
	for _, c := range allowed {
		flag[c] = true
	}
	for _, word := range words {
		for _, c := range word {
			if !flag[c] {
				ans -= 1
				break
			}
		}
	}

	return ans
}

rust

impl Solution {
    pub fn count_consistent_strings(allowed: String, words: Vec<String>) -> i32 {
        let mut ans = words.len() as i32;

        let mut flag = vec![false; 128];
        allowed.as_bytes().iter().for_each(|c| {
            flag[*c as usize] = true;
        });

        words.iter().for_each(|word| {
            for c in word.as_bytes() {
                if !flag[*c as usize] {
                    ans -= 1;
                    break;
                }
            }
        });

        ans
    }
}

在这里插入图片描述


原题传送门:https://leetcode-cn.com/problems/count-the-number-of-consistent-strings/


非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~