题目地址:
https://leetcode.com/problems/count-the-number-of-consistent-strings/
给定一个字符串
a
a
a和一个字符串数组
A
A
A,问
A
A
A有多少个字符串只含
a
a
a中的字符。
代码如下:
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int countConsistentStrings(String allowed, String[] words) {
Set<Character> set = new HashSet<>();
for (int i = 0; i < allowed.length(); i++) {
set.add(allowed.charAt(i));
}
int res = 0;
for (String word : words) {
boolean ok = true;
for (int i = 0; i < word.length(); i++) {
if (!set.contains(word.charAt(i))) {
ok = false;
break;
}
}
if (ok) {
res++;
}
}
return res;
}
}
时间复杂度
O
(
l
a
+
l
A
s
)
O(l_a+l_As)
O(la+lAs),
s
s
s是
A
A
A中最长字符串长度,空间
O
(
l
a
)
O(l_a)
O(la)。