Count the Number of Consistent Strings

The problem is asking us to find the number of consistent strings in the given words list. A string is consistent if all the characters in that string appear in the string allowed.

Here’s the step-by-step method to solve this problem:

  1. Convert the allowed string into a set of characters, so that you can check for the existence of a character in the allowed string efficiently.
  2. Iterate through the words and check if each word is consistent. To do this, you’ll look at each character in the word and see if it’s in the allowed set. If you find a character that is not in the allowed set, the word is not consistent.
  3. Count the number of consistent words and return that count.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
        # Convert the allowed string into a set
        allowed_chars = set(allowed)

        # Initialize the count of consistent strings
        consistent_count = 0

        # Iterate through the words
        for word in words:
            # Check if the word is consistent
            if all(char in allowed_chars for char in word):
                consistent_count += 1

        return consistent_count

Explanation:

  • allowed_chars = set(allowed) converts the allowed string into a set of characters, which enables constant time complexity for checking if a character exists in the set.
  • if all(char in allowed_chars for char in word): checks if every character in the word is in the allowed set. If it is, the word is consistent, and the count is incremented.
  • Finally, the code returns the count of consistent strings.