1684 - Count the Number of Consistent Strings

 C++

  • class Solution {
    public:
        int countConsistentStrings(string allowed, vector<string>& words) {
            bitset<26> s;
            for (auto& c : allowed) s[c - 'a'] = 1;
            int ans = 0;
            auto check = [&](string& w) {
                for (auto& c : w)
                    if (!s[c - 'a']) return false;
                return true;
            };
            for (auto& w : words) ans += check(w);
            return ans;
        }
    };

JAVA

  • class Solution {
        public int countConsistentStrings(String allowed, String[] words) {
            boolean[] s = new boolean[26];
            for (char c : allowed.toCharArray()) {
                s[c - 'a'] = true;
            }
            int ans = 0;
            for (String w : words) {
                if (check(w, s)) {
                    ++ans;
                }
            }
            return ans;
        }
    
        private boolean check(String w, boolean[] s) {
            for (int i = 0; i < w.length(); ++i) {
                if (!s[w.charAt(i) - 'a']) {
                    return false;
                }
            }
            return true;
        }
    }

Comments