Complexity
Runtime
Space
Code
C++
class Solution {
public:
bool halvesAreAlike(string s) {
int n = s.length();
int c1 = 0;
int c2 = 0;
std::set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
for (size_t i = 0; i < n; ++i) {
if (vowels.find(s[i]) != vowels.end()) {
if (i < n / 2) {
c1 += 1;
} else {
c2 += 1;
}
}
}
return c1 == c2;
}
};C
bool in(char c) {
char vowels[] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
for(int i = 0; i < 10; i++) {
if (c == vowels[i]) {
return true;
} // end if
} // end for
return false;
} // end func
bool halvesAreAlike(char* s) {
int c1 = 0;
int c2 = 0;
int n = strlen(s);
int mid = n / 2;
for (int i = 0; i < n; i++) {
if (in(s[i])) {
if (i < mid) {
c1 += 1;
} else {
c2 += 1;
}
}
} // end for
return c1 == c2;
} // end functionPython
class Solution:
def halvesAreAlike(self, s: str) -> bool:
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
c1, c2 = 0, 0
mid = len(s) // 2
for i, c in enumerate(s):
if c in vowels:
if i < mid:
c1 += 1
else:
c2 += 1
return c1 == c2Notes
- s → a 1st half, b 2nd half
- alike: vowel count is same
Cards
START Basic Front: Determine If String Halves Are Alike Back: Hard coded vowels to check in time first and 2nd halves, respectively.
END