|
57 | 57 |
|
58 | 58 | ## Solutions
|
59 | 59 |
|
60 |
| -### Solution 1 |
| 60 | +### Solution 1: Hash Table or Array |
| 61 | + |
| 62 | +We use a hash table or array $s$ to record the characters that appear in the string $word$. Then we traverse the 26 letters. If both the lowercase and uppercase letters appear in $s$, the count of special characters is incremented by one. |
| 63 | + |
| 64 | +Finally, return the count of special characters. |
| 65 | + |
| 66 | +The time complexity is $O(n + |\Sigma|)$, and the space complexity is $O(|\Sigma|)$. Where $n$ is the length of the string $word$, and $|\Sigma|$ is the size of the character set. In this problem, $|\Sigma| \leq 128$. |
61 | 67 |
|
62 | 68 | <!-- tabs:start -->
|
63 | 69 |
|
64 | 70 | ```python
|
65 |
| - |
| 71 | +class Solution: |
| 72 | + def numberOfSpecialChars(self, word: str) -> int: |
| 73 | + s = set(word) |
| 74 | + return sum(a in s and b in s for a, b in zip(ascii_lowercase, ascii_uppercase)) |
66 | 75 | ```
|
67 | 76 |
|
68 | 77 | ```java
|
69 |
| - |
| 78 | +class Solution { |
| 79 | + public int numberOfSpecialChars(String word) { |
| 80 | + boolean[] s = new boolean['z' + 1]; |
| 81 | + for (int i = 0; i < word.length(); ++i) { |
| 82 | + s[word.charAt(i)] = true; |
| 83 | + } |
| 84 | + int ans = 0; |
| 85 | + for (int i = 0; i < 26; ++i) { |
| 86 | + if (s['a' + i] && s['A' + i]) { |
| 87 | + ++ans; |
| 88 | + } |
| 89 | + } |
| 90 | + return ans; |
| 91 | + } |
| 92 | +} |
70 | 93 | ```
|
71 | 94 |
|
72 | 95 | ```cpp
|
73 |
| - |
| 96 | +class Solution { |
| 97 | +public: |
| 98 | + int numberOfSpecialChars(string word) { |
| 99 | + vector<bool> s('z' + 1); |
| 100 | + for (char& c : word) { |
| 101 | + s[c] = true; |
| 102 | + } |
| 103 | + int ans = 0; |
| 104 | + for (int i = 0; i < 26; ++i) { |
| 105 | + ans += s['a' + i] && s['A' + i]; |
| 106 | + } |
| 107 | + return ans; |
| 108 | + } |
| 109 | +}; |
74 | 110 | ```
|
75 | 111 |
|
76 | 112 | ```go
|
| 113 | +func numberOfSpecialChars(word string) (ans int) { |
| 114 | + s := make([]bool, 'z'+1) |
| 115 | + for _, c := range word { |
| 116 | + s[c] = true |
| 117 | + } |
| 118 | + for i := 0; i < 26; i++ { |
| 119 | + if s['a'+i] && s['A'+i] { |
| 120 | + ans++ |
| 121 | + } |
| 122 | + } |
| 123 | + return |
| 124 | +} |
| 125 | +``` |
77 | 126 |
|
| 127 | +```ts |
| 128 | +function numberOfSpecialChars(word: string): number { |
| 129 | + const s: boolean[] = Array.from({ length: 'z'.charCodeAt(0) + 1 }, () => false); |
| 130 | + for (let i = 0; i < word.length; ++i) { |
| 131 | + s[word.charCodeAt(i)] = true; |
| 132 | + } |
| 133 | + let ans: number = 0; |
| 134 | + for (let i = 0; i < 26; ++i) { |
| 135 | + if (s['a'.charCodeAt(0) + i] && s['A'.charCodeAt(0) + i]) { |
| 136 | + ++ans; |
| 137 | + } |
| 138 | + } |
| 139 | + return ans; |
| 140 | +} |
78 | 141 | ```
|
79 | 142 |
|
80 | 143 | <!-- tabs:end -->
|
|
0 commit comments