Java C++题解leetcode 1684统计一致字符串的数目示例
作者:AnjaVon 时间:2023-04-23 09:06:31
题目
题目要求
思路:模拟
用一个哈希表记录可出现的字母,然后逐一遍历每个单词每个字母,符合条件则结果加一。
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
}
}
来源:https://juejin.cn/post/7163622866301222943
标签:Java,C++,LeetCode,统计数目,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java文件操作实例详解
2023-11-25 10:29:40
![](https://img.aspxhome.com/file/2023/2/59562_0s.jpg)
Android中应用多进程的整理总结
2022-05-05 04:25:21
Java开发工具IntelliJ IDEA安装图解
2022-06-14 02:30:20
![](https://img.aspxhome.com/file/2023/4/69934_0s.png)
SpringCloud eureka(server)微服务集群搭建过程
2023-05-22 15:08:55
![](https://img.aspxhome.com/file/2023/4/69104_0s.jpg)
Android调试出现The selected device is incompatible问题解决
2023-08-11 12:58:34
![](https://img.aspxhome.com/file/2023/5/137935_0s.jpg)
Android Fragment实现顶部、底部导航栏
2023-03-26 06:27:58
![](https://img.aspxhome.com/file/2023/7/94267_0s.gif)
spring cloud oauth2 feign 遇到的坑及解决
2022-06-15 13:06:06
![](https://img.aspxhome.com/file/2023/9/89619_0s.png)
Java简单计时的实现案例(可以用来限时循环)
2023-02-01 21:39:19
C# 使用Fluent API 创建自己的DSL(推荐)
2022-03-30 23:36:48
Android中SQLite 使用方法详解
2022-02-08 15:31:37
![](https://img.aspxhome.com/file/2023/0/139370_0s.png)
SpringCloud之微服务容错的实现
2023-11-29 02:02:22
![](https://img.aspxhome.com/file/2023/5/60775_0s.png)
Android异常处理最佳实践
2021-06-15 20:17:12
java使用dom4j生成与解析xml文档的方法示例
2022-06-18 23:41:56
![](https://img.aspxhome.com/file/2023/4/89634_0s.png)
java判断某个点是否在所画多边形/圆形内
2022-09-30 23:50:45
Spring Boot 启动加载数据 CommandLineRunner的使用
2021-06-17 12:52:21
C#动态编译并执行字符串样例
2022-02-10 22:26:53
Java常用锁synchronized和ReentrantLock的区别
2023-06-01 04:42:21
![](https://img.aspxhome.com/file/2023/3/116803_0s.webp)
利用Matlab复刻羊了个羊小游戏
2021-10-10 17:13:05
![](https://img.aspxhome.com/file/2023/8/131948_0s.jpg)
浅谈android Fragment横竖屏翻转对重新加载的要求
2023-07-27 21:55:28
C#将PPT文件转换成PDF文件
2022-09-08 20:33:21