Skip to content

3120. Count the Number of Special Characters I 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int numberOfSpecialChars(string word) {
    int ans = 0;
    vector<bool> lower(26);
    vector<bool> upper(26);

    for (const char c : word)
      if (islower(c))
        lower[c - 'a'] = true;
      else
        upper[c - 'A'] = true;

    for (int i = 0; i < 26; ++i)
      if (lower[i] && upper[i])
        ++ans;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int numberOfSpecialChars(String word) {
    int ans = 0;
    boolean[] lower = new boolean[26];
    boolean[] upper = new boolean[26];

    for (final char c : word.toCharArray())
      if (Character.isLowerCase(c))
        lower[c - 'a'] = true;
      else
        upper[c - 'A'] = true;

    for (int i = 0; i < 26; ++i)
      if (lower[i] && upper[i])
        ++ans;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def numberOfSpecialChars(self, word: str) -> int:
    lower = collections.defaultdict(bool)
    upper = collections.defaultdict(bool)

    for c in word:
      if c.islower():
        lower[c] = True
      else:
        upper[c] = True

    return sum(lower[a] and upper[b]
               for a, b in zip(string.ascii_lowercase,
                               string.ascii_uppercase))