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.
Input: s ="textbook"Output: falseExplanation: a ="t _e_ xt" and b ="b _oo_ k". a has 1 vowel whereas b has 2. Therefore, they are not alike.Notice that the vowel o is counted twice.
classSolution {
public:bool halvesAreAlike(string s) {
string v ="aeiouAEIOU";
int n = s.size(), cnt1 =0, cnt2 =0;
for (int i =0; i < n /2; ++i) if (v.find(s[i]) != string::npos) ++cnt1;
for (int i = n /2; i < n; ++i) if (v.find(s[i]) != string::npos) ++cnt2;
return cnt1 == cnt2;
}
};
classSolution {
publicbooleanhalvesAreAlike(String s) {
String v ="aeiouAEIOU";
int n = s.length(), cnt1 = 0, cnt2 = 0;
for (int i = 0; i < n / 2; ++i) if (v.indexOf(s.charAt(i)) !=-1) ++cnt1;
for (int i = n / 2; i < n; ++i) if (v.indexOf(s.charAt(i)) !=-1) ++cnt2;
return cnt1 == cnt2;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funhalvesAreAlike(s: String): Boolean {
val v = "aeiouAEIOU"val n = s.length
var cnt1 = 0var cnt2 = 0for (i in0 until n / 2) if (v.contains(s[i])) cnt1++for (i in n / 2 until n) if (v.contains(s[i])) cnt2++return cnt1 == cnt2
}
}
1
2
3
4
5
6
7
classSolution:
defhalvesAreAlike(self, s: str) -> bool:
v = set('aeiouAEIOU')
n = len(s)
cnt1 = sum(1for c in s[:n//2] if c in v)
cnt2 = sum(1for c in s[n//2:] if c in v)
return cnt1 == cnt2
1
2
3
4
5
6
7
8
9
10
impl Solution {
pubfnhalves_are_alike(s: String) -> bool {
let v ="aeiouAEIOU".chars().collect::<std::collections::HashSet<_>>();
let n = s.len();
let s = s.chars().collect::<Vec<_>>();
let cnt1 = s[..n/2].iter().filter(|c| v.contains(c)).count();
let cnt2 = s[n/2..].iter().filter(|c| v.contains(c)).count();
cnt1 == cnt2
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
halvesAreAlike(s: string):boolean {
constv=newSet('aeiouAEIOU');
constn=s.length;
letcnt1=0, cnt2=0;
for (leti=0; i<n/2; ++i) if (v.has(s[i])) ++cnt1;
for (leti=n/2; i<n; ++i) if (v.has(s[i])) ++cnt2;
returncnt1===cnt2;
}
}