#力扣:1684. 统计一致字符串的数目@FDDLC

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 
#include 

using namespace std;

class Solution {
public:
    int countConsistentStrings(string allowed, vector &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 = 0
        for s in words:
            flag = True
            for c in s:
                if c not in allowedSet:
                    flag = False
                    break
            if flag:
                cnt += 1
        return 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 main

func countConsistentStrings(allowed string, words []string) int {
	var isAllowed [26]bool
	for _, c := range allowed {
		isAllowed[c-'a'] = true
	}
	cnt := 0
	for _, s := range words {
		flag := true
		for _, c := range s {
			if !isAllowed[c-'a'] {
				flag = false
				break
			}
		}
		if flag {
			cnt++
		}
	}
	return cnt
}

你可能感兴趣的:(力扣刷题:Java,C++,Python,JS,Go,leetcode,java,算法)