Java C++题解leetcode 1684统计一致字符串的数目示例
更新时间:2023年01月16日 11:47:21 作者:AnjaVon
这篇文章主要为大家介绍了Java C++题解leetcode 1684统计一致字符串的数目示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
题目


思路:模拟
- 用一个哈希表记录可出现的字母,然后逐一遍历每个单词每个字母,符合条件则结果加一。
Java
class Solution {
public int countConsistentStrings(String allowed, String[] words) {
boolean[] hash = new boolean[26];
for (var a : allowed.toCharArray())
hash[a - 'a'] = true;
int res = 0;
stop : for (var word : words) {
for (var w : word.toCharArray()) {
if (!hash[w - 'a'])
continue stop;
}
res++;
}
return res;
}
}

C++
class Solution {
public:
int countConsistentStrings(string allowed, vector<string>& words) {
int hash[26] = {0};
for (auto a : allowed)
hash[a - 'a'] = true;
int res = 0;
for (auto& word : words) {
bool ok = true;
for (auto w : word) {
if (!hash[w - 'a']) {
ok = false;
continue;
}
}
if (ok)
res++;
}
return res;
}
};

Rust
impl Solution {
pub fn count_consistent_strings(allowed: String, words: Vec<String>) -> i32 {
let mut hash = vec![false; 26];
for a in allowed.as_bytes().iter() {
hash[(a - b'a') as usize] = true;
}
let mut res = 0;
for word in words {
let mut ok = true;
for w in word.as_bytes().iter() {
if !hash[(w - b'a') as usize] {
ok = false;
continue;
}
}
if ok {
res += 1;
}
}
res
}
}

以上就是Java C++题解leetcode 1684统计一致字符串的数目示例的详细内容,更多关于Java C++统计一致字符串数目的资料请关注脚本之家其它相关文章!
相关文章
使用springCloud+nacos集成seata1.3.0搭建过程
这篇文章主要介绍了使用springCloud+nacos集成seata1.3.0搭建过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-08-08
Spring Boot集成MinIO进行文件存储和管理的详细步骤
这篇文章主要介绍了Spring Boot集成MinIO进行文件存储和管理的详细步骤,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧2025-04-04
Spring中的ApplicationContext与BeanFactory详解
这篇文章主要介绍了Spring中的ApplicationContext与BeanFactory详解,Spring的IoC容器就是一个实现了BeanFactory接口的可实例化类,事实上, Spring提供了两种不同的容器,一种是最基本的BeanFactory,另一种是扩展的ApplicationContext,需要的朋友可以参考下2024-01-01
Java BufferedImage转换为MultipartFile方式
这篇文章主要介绍了Java BufferedImage转换为MultipartFile方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-09-09


最新评论