Skip to content

Commit cea4929

Browse files
solves #3120: Count the Number of Special Characters I in java
1 parent f194fb4 commit cea4929

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -905,7 +905,7 @@
905905
| 3105 | [Longest Strictly Increasing or Strictly Decreasing Subarray](https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray) | [![Java](assets/java.png)](src/LongestStrictlyIncreasingOrStrictlyDecreasingSubarray.java) | |
906906
| 3110 | [Score of a String](https://leetcode.com/problems/score-of-a-string) | [![Java](assets/java.png)](src/ScoreOfAString.java) | |
907907
| 3114 | [Latest Time You Can Obtain After Replacing Characters](https://leetcode.com/problems/latest-time-you-can-obtain-after-replacing-characters) | [![Java](assets/java.png)](src/LatestTimeYouCanObtainAfterReplacingCharacters.java) | |
908-
| 3120 | [Count the Number of Special Characters I](https://leetcode.com/problems/count-the-number-of-special-characters-i) | | |
908+
| 3120 | [Count the Number of Special Characters I](https://leetcode.com/problems/count-the-number-of-special-characters-i) | [![Java](assets/java.png)](src/CountTheNumberOfSpecialCharactersI.java) | |
909909
| 3127 | [Make a Square with the Same Color](https://leetcode.com/problems/make-a-square-with-the-same-color) | | |
910910
| 3131 | [Find the Integer Added to Array I](https://leetcode.com/problems/find-the-integer-added-to-array-i) | | |
911911
| 3136 | [Valid Word](https://leetcode.com/problems/valid-word) | | |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// https://leetcode.com/problems/count-the-number-of-special-characters-i
2+
// T: O(N)
3+
// S: O(1)
4+
5+
import java.util.HashSet;
6+
import java.util.Set;
7+
8+
public class CountTheNumberOfSpecialCharactersI {
9+
public int numberOfSpecialChars(String word) {
10+
final Set<Character> characters = new HashSet<>();
11+
final Set<Character> alreadyCounted = new HashSet<>();
12+
int specialChars = 0;
13+
14+
for (int i = 0 ; i < word.length() ; i++) {
15+
characters.add(word.charAt(i));
16+
if (characters.contains(inverse(word.charAt(i))) && !alreadyCounted.contains(word.charAt(i))) {
17+
specialChars++;
18+
alreadyCounted.add(word.charAt(i));
19+
alreadyCounted.add(inverse(word.charAt(i)));
20+
}
21+
}
22+
23+
return specialChars;
24+
}
25+
26+
private static char inverse(char c) {
27+
if (Character.isLowerCase(c)) {
28+
return Character.toUpperCase(c);
29+
}
30+
return Character.toLowerCase(c);
31+
}
32+
}

0 commit comments

Comments
 (0)