Determine if String Halves Are Alike LeetCode solution in Java

1
class Solution {
2
public boolean halvesAreAlike(String s) {
3
// add vowels to the set
4
Set<Character> set = new HashSet<>();
5
set.add('a');
6
set.add('e');
7
set.add('i');
8
set.add('o');
9
set.add('u');
10
set.add('A');
11
set.add('E');
12
set.add('I');
13
set.add('O');
14
set.add('U');
15

16
// find the mid
17
int mid = s.length() / 2;
18
int count = 0;
19
// increment the count for left half, decrement count for the second half if its a vowel
20
for (int i = 0; i < s.length(); i++)
21
count += (set.contains(s.charAt(i))) ? ((i < mid) ? 1 : -1) : 0;
22
// finally count should be 0 to match left and right half
23
return count == 0;
24
}
25
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0