1684. 统计一致字符串的数目 - 力扣(LeetCode)
一、Java
class Solution {public int countConsistentStrings(String allowed, String[] words) {boolean[] isAllowed = new boolean[26];for(int i = 0; i < allowed.length(); i++) isAllowed[allowed.charAt(i)-'a'] = true;int cnt = 0;for(String s: words) {boolean flag = true;for(int i = s.length() - 1; i >= 0; i--){if(!isAllowed[s.charAt(i) - 'a']){flag = false;break;}}if(flag)cnt++;}return cnt;}
}
二、C++
#include <string>
#include <vector>using namespace std;class Solution {
public:int countConsistentStrings(string allowed, vector<string> &words) {bool isAllowed[26] = {};for (char c: allowed) isAllowed[c - 'a'] = true;int cnt = 0;for (string s: words) {bool flag = true;for (char c: s) {if (!isAllowed[c - 'a']) {flag = false;break;}}if(flag) cnt++;}return cnt;}
};
三、Python
from typing import List
class Solution:def countConsistentStrings(self, allowed: str, words: List[str]) -> int:allowedSet = set(allowed)cnt = 0for s in words:flag = Truefor c in s:if c not in allowedSet:flag = Falsebreakif flag:cnt += 1return cnt
四、JavaScript
var countConsistentStrings = function (allowed, words) {allowedSet = new Set(allowed);let cnt = 0;for (let s of words) {let flag = true;for (let c of s) {if (!allowedSet.has(c)) {flag = false;break;}}if (flag) cnt++;}return cnt;
};
五、Go
package mainfunc countConsistentStrings(allowed string, words []string) int {var isAllowed [26]boolfor _, c := range allowed {isAllowed[c-'a'] = true}cnt := 0for _, s := range words {flag := truefor _, c := range s {if !isAllowed[c-'a'] {flag = falsebreak}}if flag {cnt++}}return cnt
}