Determine if String Halves Are Alike
Problem
Given an even-length string s, decide if its first half and second half contain the same number of vowels (aeiouAEIOU).
s = "book"truedef halves_are_alike(s):
vowels = set('aeiouAEIOU')
half = len(s) // 2
a = sum(1 for c in s[:half] if c in vowels)
b = sum(1 for c in s[half:] if c in vowels)
return a == b
function halvesAreAlike(s) {
const v = new Set("aeiouAEIOU");
const half = s.length / 2;
let a = 0, b = 0;
for (let i = 0; i < half; i++) if (v.has(s[i])) a++;
for (let i = half; i < s.length; i++) if (v.has(s[i])) b++;
return a === b;
}
class Solution {
public boolean halvesAreAlike(String s) {
String v = "aeiouAEIOU";
int half = s.length() / 2, a = 0, b = 0;
for (int i = 0; i < half; i++) if (v.indexOf(s.charAt(i)) >= 0) a++;
for (int i = half; i < s.length(); i++) if (v.indexOf(s.charAt(i)) >= 0) b++;
return a == b;
}
}
bool halvesAreAlike(string s) {
string v = "aeiouAEIOU";
int half = s.size() / 2, a = 0, b = 0;
for (int i = 0; i < half; i++) if (v.find(s[i]) != string::npos) a++;
for (int i = half; i < (int)s.size(); i++) if (v.find(s[i]) != string::npos) b++;
return a == b;
}
Explanation
The question is simply whether the first half and the second half of the string hold the same number of vowels. So we just count vowels in each half and compare the two totals.
First we build a quick lookup vowels containing all ten vowels (both cases). We find the midpoint with half = len(s) // 2. Then a counts vowels in s[:half] and b counts vowels in s[half:]. The answer is a == b.
Using a set for the vowels means each "is this a vowel?" check is instant, so counting is a simple sweep.
Example: s = "book". The halves are "bo" and "ok". Each has exactly one vowel (o), so a == b == 1 and the result is true.
We touch every character once while counting, which makes the whole check linear in the length of the string.