Leetcode 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 determine if these halves are alike.
Two strings are considered 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 the two halves of the string are alike; otherwise, return false
.
s = "book"
true
"bo"
and "ok"
each have 1 vowel. Therefore, they are alike.s = "text"
false
"te"
has 1 vowel, "xt"
has 0 vowels. Therefore, they are not alike.2 <= s.length <= 1000
s.length
is even.s
consists of uppercase and lowercase letters.s
will always have an even length.s
into two halves.true
if the counts are equal, otherwise return false
.#include <iostream>
#include <unordered_set>
#include <cctype>
bool halvesAreAlike(std::string s) {
std::unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
int n = s.length();
int half = n / 2;
int count1 = 0, count2 = 0;
for (int i = 0; i < half; ++i) {
if (vowels.count(s[i])) ++count1;
if (vowels.count(s[half + i])) ++count2;
}
return count1 == count2;
}
int main() {
std::string s1 = "book";
std::string s2 = "text";
std::cout << std::boolalpha << halvesAreAlike(s1) << std::endl; // Output: true
std::cout << std::boolalpha << halvesAreAlike(s2) << std::endl; // Output: false
return 0;
}
The time complexity of this solution is O(n), where n
is the length of the string. This is because we need to iterate through each character of the string once.
The space complexity is O(1) because we’re using only a constant amount of extra space (for the set of vowels and a few integer counters).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?