Post

3405 Count The Number Of Special Characters Ii

3405 Count The Number Of Special Characters Ii

Count the Number of Special Characters II image

You are given a string word. A letter c is called special if it appears both in lowercase and uppercase in word, and every lowercase occurrence of c appears before the first uppercase occurrence of c.

Return the number of* special letters in *word.

 

Example 1:

Input: word = “aaAbcBC”

Output: 3

Explanation:

The special characters are ‘a’, ‘b’, and ‘c’.

Example 2:

Input: word = “abc”

Output: 0

Explanation:

There are no special characters in word.

Example 3:

Input: word = “AbBCab”

Output: 0

Explanation:

There are no special characters in word.

 

Constraints:

1
2
1 <= word.length <= 2 * 105
word consists of only lowercase and uppercase English letters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class Solution:
    def numberOfSpecialChars(self, word: str) -> int:
        last_low = {}
        first_up = {}
        for i, c in enumerate(word):
            if c.islower():
                last_low[c] = i
            else:
                if c not in first_up:
                    first_up[c] = i
        ans = 0
        for c in string.ascii_lowercase:
            if (
                c in last_low
                and c.upper() in first_up
                and last_low[c] < first_up[c.upper()]
            ):
                ans += 1
        return ans



This post is licensed under CC BY 4.0 by the author.