Skip to content

3120. Count the Number of Special Characters I

Description

You are given a string word. A letter is called special if it appears both in lowercase and uppercase in word.

Return the number ofspecial letters inword.

 

Example 1:

Input: word = "aaAbcBC"

Output: 3

Explanation:

The special characters in word are 'a', 'b', and 'c'.

Example 2:

Input: word = "abc"

Output: 0

Explanation:

No character in word appears in uppercase.

Example 3:

Input: word = "abBCab"

Output: 1

Explanation:

The only special character in word is 'b'.

 

Constraints:

  • 1 <= word.length <= 50
  • word consists of only lowercase and uppercase English letters.

 

Solutions

Solution: Hash Table

  • Time complexity: O(n)
  • Space complexity: O(n)

 

JavaScript

js
/**
 * @param {string} word
 * @return {number}
 */
const numberOfSpecialChars = function (word) {
  const BASE_CODE = 'a'.charCodeAt(0);
  const charSet = new Set(word);
  let mask = 0;
  let result = 0;

  for (const char of charSet) {
    const code = char.toLowerCase().charCodeAt(0) - BASE_CODE;

    if ((mask >> code) & 1) {
      result += 1;
    }

    mask |= 1 << code;
  }

  return result;
};

Released under the MIT license