[LeetCode] Determine if String Halves Are Alike

1704. Determine if String Halves Are Alike

You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

Two strings are alike if they have the same number of vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘A’, ‘E’, ‘I’, ‘O’, ‘U’). Notice that s contains uppercase and lowercase letters.

Return true if a and b are alike. Otherwise, return false.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool halvesAreAlike(string s) {
int cnt = 0;
unordered_set<char> v{'a','e','i','o','u','A','E','I','O','U'};
for(int i = 0; i < s.length(); i++) {
if(!v.count(s[i])) continue;
if(i < s.length() / 2) cnt += 1;
else cnt -= 1;
}
return cnt == 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/01/PS/LeetCode/determine-if-string-halves-are-alike/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.