Member-only story

Leetcode 1704: Determine if String Halves Are Alike. All main languages

Pierre-Marie Poitevin
3 min readDec 27, 2020

--

In this Leetcode problem, we need to count the vowels in each half of the string in input. If the number of vowels is the same in both halves, we return true, we return false otherwise.

Here is the implementation for the all the main backend languages, in alphabetical order:

C++

class Solution {
public:
bool halvesAreAlike(string s) {
int n = s.length();
int count = 0;
set<char> vowels;
vowels.insert('a');
vowels.insert('e');
vowels.insert('i');
vowels.insert('o');
vowels.insert('u');
vowels.insert('A');
vowels.insert('E');
vowels.insert('I');
vowels.insert('O');
vowels.insert('U');
for (int i = 0; i < n/2; i++) {
if (vowels.find(s[i]) != vowels.end()) {
count++;
}
}
for (int i = n/2; i < n; i++) {
if (vowels.find(s[i]) != vowels.end()) {
count--;
}
}
return (count == 0);
}
};

Go

func halvesAreAlike(s string) bool {
vowels:= make(map[rune]bool)
vowels['a'] = true;
vowels['e'] = true;
vowels['i'] = true;
vowels['o'] = true;
vowels['u'] = true;
vowels['A'] = true;
vowels['E'] = true;
vowels['I'] = true;
vowels['O'] = true;
vowels['U'] = true;
runeS := []rune(s);
n := len(runeS)…

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet