Check if a String Is an Acronym of Words

We can implement the isAcronym function to check whether the string s is an acronym of the words in the array words. We’ll do this by extracting the first character of each word and concatenating them to form a new string. Then, we’ll compare this new string with s. If they are the same, s is an acronym of words; otherwise, it’s not.

Here’s the implementation:

1
2
3
4
5
6
7
class Solution:
    def isAcronym(self, words: List[str], s: str) -> bool:
        # Concatenate the first character of each word in words
        acronym = ''.join(word[0] for word in words)

        # Check if the concatenated string is equal to s
        return acronym == s

Explanation

  1. Create the Acronym: We iterate through each word in words and take the first character, concatenating them to form a string acronym.
  2. Compare with s: We check whether acronym is equal to s. If it is, s is the acronym of words, and we return true; otherwise, we return false.

The code has a time complexity of O(n), where n is the total number of characters in the words array. It follows the constraints provided and returns whether s is an acronym of words or not.