leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit d8d12c24604d7ac3d5382998cc9550e503726d1e
parent dc009d327e278bea38e4c981404a897accf278b8
Author: Jack Sangdahl <jack@pngu.org>
Date:   Wed, 27 May 2026 09:09:37 -0600

3121. count the number of special characters 2

Diffstat:
Acount_num_special_char2.c | 40++++++++++++++++++++++++++++++++++++++++
Acount_num_special_char2.py | 25+++++++++++++++++++++++++
2 files changed, 65 insertions(+), 0 deletions(-)

diff --git a/count_num_special_char2.c b/count_num_special_char2.c @@ -0,0 +1,40 @@ +// 3121. Count the Number of Special Characters II +#include "leetcode.h" + +/* + * 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 occurence of + * 'c' appears before the first uppercase occurence of 'c'. return the number of + * special letters in 'word'. + */ + +int numberOfSpecialChars(char *word) { + uint32_t lower = 0, upper = 0, invalid = 0; + for (int i = 0; word[i] != '\0'; i++) { + char curr = word[i]; + bool lowercase = curr > 'Z'; + int idx = curr - 'A' - (lowercase << 5); + if (lowercase) + lower |= (1 << idx); + else + upper |= (1 << idx); + invalid |= ((uint32_t)lowercase << idx) & upper; + } + uint32_t common = lower & upper & ~invalid; + return __builtin_popcount(common); +} + +int main() { + char *w1 = "aaAbcBC"; + char *w2 = "abc"; + char *w3 = "AbBCab"; + int r1 = numberOfSpecialChars(w1); + int r2 = numberOfSpecialChars(w2); + int r3 = numberOfSpecialChars(w3); + printf("%d\n", r1); + assert(r1 == 3); + printf("%d\n", r2); + assert(r2 == 0); + printf("%d\n", r3); + assert(r3 == 0); +} diff --git a/count_num_special_char2.py b/count_num_special_char2.py @@ -0,0 +1,25 @@ +# 3121. Count the Number of Special Characters II +from string import ascii_lowercase + +""" +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 occurence of +'c' appears before the first uppercase occurence of 'c'. return the number of +special letters in 'word'. +""" + + +class Solution: + def numberOfSpecialChars(self, word: str) -> int: + d = {j: i for i, j in enumerate(word) if j.islower()} + p = {j: len(word) - i for i, j in enumerate(reversed(word)) if j.isupper()} + return sum( + d.get(i, float("inf")) < p.get(i.upper(), 0) for i in ascii_lowercase + ) + + +if __name__ == "__main__": + obj = Solution() + print(obj.numberOfSpecialChars(word="aaAbcBC")) + print(obj.numberOfSpecialChars(word="abc")) + print(obj.numberOfSpecialChars(word="AbBCab"))